﻿using GPSTrackingDBV2.Entities;
using System;
using System.Linq;
using System.Data;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Collections.Generic;
using Telerik.Reporting.Processing;
using System.Drawing;

namespace WCFPointOfSaleService
{
    public class PointOfSaleService : IPointOfSaleService
    {

        public string GetVersion()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); 
        }

        public string GetSQL()
        {
            try
            {
                if (GPSTrackingDBV2.Data.DataRepository.CompaniesProvider.GetAll().Count > 0)
                    return "Connect to SQL Data Base: OK";
                else
                    return "Connect to SQL Data Base: Faild";
            }
            catch (Exception ex)
            {
                string message = "Message: "+ex.Message;
                if (ex.InnerException != null)
                    message += " Inner Exception: " + ex.InnerException;

                return "Error - " + message;
            }

        }


        public List<Entities.Stock> GetAllStock(string companyId)
        {
            TList<Stock> stockEntities = GPSTrackingDBV2.Data.DataRepository.StockProvider.GetByCompanyId(Convert.ToInt32(companyId));
            List<Entities.Stock> stockList = new List<Entities.Stock>();
            foreach (Stock entity in stockEntities)
            {
                Entities.Stock stockEntity = new Entities.Stock();
                stockEntity.CompanyId = entity.CompanyId;
                stockEntity.StockId = entity.StockId;
                stockEntity.Name = entity.Name;
                stockEntity.Quantity = entity.Quantity;
                stockEntity.Price = entity.Price;

                stockList.Add(stockEntity);
            }

            return stockList;

        }

        public Entities.Users IdentifiedUser(int companyID, string username, string password)
        {
            Entities.Users UserEntityReturn = new Entities.Users();

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                GPSTrackingDBV2.Entities.Users UserEntity;

                UserEntity = GPSTrackingDBV2.Data.DataRepository.UsersProvider.GetByUsernameCompanyId(username, companyID);

                if (UserEntity != null)
                {
                    if (UserEntity.Password == password)
                    {
                        UserEntityReturn.Username = UserEntity.Username;
                        UserEntityReturn.Name = UserEntity.Name;
                        UserEntityReturn.Identification = UserEntity.Identification;
                        UserEntityReturn.FirstName = UserEntity.FirstName;
                        UserEntityReturn.LastName = UserEntity.LastName;
                        UserEntityReturn.IsActive = UserEntity.IsActive;
                        UserEntityReturn.Exists = true;
                        UserEntityReturn.IsIdentified = true;

                    }
                    else
                    {
                        UserEntityReturn.IsIdentified = false;
                        UserEntityReturn.Exists = true;
                    }
                }
                else
                    UserEntityReturn.Exists = false;

            }
            return UserEntityReturn;
        }

        public Entities.Admin IdentifiedAdmin(int companyID, string adminUsername, string password)
        {
            Entities.Admin adminEntityReturn = new Entities.Admin();

            if (!string.IsNullOrEmpty(adminUsername) && !string.IsNullOrEmpty(password))
            {
                GPSTrackingDBV2.Entities.Administrators administratorsEntity;

                administratorsEntity = GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.GetByAdminUsernameCompanyId(adminUsername, companyID);

                if (administratorsEntity != null)
                {
                    if (administratorsEntity.Password == password)
                    {
                        adminEntityReturn.AdminUsername = administratorsEntity.AdminUsername;
                        adminEntityReturn.IsActive = administratorsEntity.IsActive;
                        adminEntityReturn.Exists = true;
                        adminEntityReturn.IsIdentified = true;

                    }
                    else
                    {
                        adminEntityReturn.IsIdentified = false;
                        adminEntityReturn.Exists = true;
                    }
                }
                else
                    adminEntityReturn.Exists = false;

            }
            return adminEntityReturn;
        }

        public List<Entities.Menu> GetApplicationMenu(int companyID, string username)
        {
            Entities.Menu menuEntity = new Entities.Menu();
            List<Entities.Menu> menuEntitiesReturn = new List<Entities.Menu>();

            try
            {
                DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.MenuProvider.GetApplicationsMenu(companyID, username);

                foreach (DataRow row in dt.Rows)
                {
                    menuEntity = new Entities.Menu();
                    menuEntity.Username = username;
                    menuEntity.ApplicationId = int.Parse(row["Page"].ToString());
                    menuEntity.Name = row["Name"].ToString();
                    menuEntitiesReturn.Add(menuEntity);
                }
            }
            catch (Exception ex) {
                menuEntity.Message = ex.Message;
                menuEntitiesReturn.Add(menuEntity);
            }

            return menuEntitiesReturn;

        }

        public Entities.Aplication GetAppPurchase(string guid)
        {
            Entities.Aplication aplicationEntityReturn = new Entities.Aplication();

            /*if (!string.IsNullOrEmpty(adminUsername) && !string.IsNullOrEmpty(password))
            {
                GPSTrackingDBV2.Entities.Administrators administratorsEntity;

                administratorsEntity = GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.GetByAdminUsernameCompanyId(adminUsername, companyID);

                if (administratorsEntity != null)
                {
                    if (administratorsEntity.Password == password)
                    {
                        adminEntityReturn.AdminUsername = administratorsEntity.AdminUsername;
                        adminEntityReturn.IsActive = administratorsEntity.IsActive;
                        adminEntityReturn.Exists = true;
                        adminEntityReturn.IsIdentified = true;

                    }
                    else
                    {
                        adminEntityReturn.IsIdentified = false;
                        adminEntityReturn.Exists = true;
                    }
                }
                else
                    adminEntityReturn.Exists = false;

            }*/
            aplicationEntityReturn.Id = 1;
            aplicationEntityReturn.Name = "Clientes";
            aplicationEntityReturn.Description = "Registro de Clientes";
            aplicationEntityReturn.TotalQuantity = 10;
            aplicationEntityReturn.UsedQuantity = 5;
        
            return aplicationEntityReturn;
        }

        public Entities.Authentication Authentication(string guid, string imei)
        {
            Entities.Authentication authenticationEntity = new Entities.Authentication();

            try
            {
                if (!string.IsNullOrEmpty(guid))
                {
                    GPSTrackingDBV2.Entities.TList<Companies> companiesEntity;

                    //if (companyID != null)
                    //{
                    //    if (companyID > 0)
                    //        username = companyID + "-" + username;                    
                    //}

                    companiesEntity = GPSTrackingDBV2.Data.DataRepository.CompaniesProvider.Find("GUID = '" + guid + "'");

                    if (companiesEntity.Count > 0)
                    {
                        if (companiesEntity.Count > 1)
                        {
                            authenticationEntity.IsAuthenticate = false;
                            authenticationEntity.Message = "El guid está registrado a mas de dos empresas, el mismo es único, contacte con su administrador del servicio";
                        }
                        else
                        {
                            if (GPSTrackingDBV2Custom.Data.DataRepository.GPSStockProvider.GetByCompanyIdAndGPSImei(companiesEntity[0].CompanyId, imei).Tables[0].Rows.Count > 0)
                            {
                                authenticationEntity.IsAuthenticate = true;
                                //authenticationEntity.LocoCompanyId = 
                                authenticationEntity.CompanyId = companiesEntity[0].CompanyId;
                                authenticationEntity.LogoCompany = companiesEntity[0].Logo.ToString();
                            }
                            else
                            {
                                authenticationEntity.IsAuthenticate = false;
                                authenticationEntity.Message = "La Empresa registrada al GUID no tiene configurado correctamente el Imei: ";
                            }



                        }

                    }
                    else
                    {
                        authenticationEntity.IsAuthenticate = false;
                        authenticationEntity.Message = "No existe el guid registrado, contacte con su administrador del servicio";

                    }


                }
            }
            catch (Exception ex)
            {
                authenticationEntity.IsAuthenticate = false;
                authenticationEntity.Message = ex.Message;
            }
            return authenticationEntity;
        }

        public List<Entities.Clients> SyncClient(string action, string syncTransaction, string tick, int clientId, string name, string phone1, string phone2, float latitude, float longitude, DateTime transactionDate, string typeUserTransaction, string usernameTransaction, string uuidTransaction, int companyIdTransaction, int clientGroupId)
        {
            Entities.Clients clientEntityReturn = new Entities.Clients();
            List<Entities.Clients> clientEntitiesReturn = new List<Entities.Clients>();

            GPSTrackingDBV2.Data.TransactionManager tm;
            GPSTrackingDBV2.Entities.Clients clientEntity;
            GPSTrackingDBV2.Entities.ClientsLog clientLogEntity;
            GPSTrackingDBV2.Entities.ClientsLogByUuid clientsLogByUuidEntity;
            long newTick;

            switch (action)
            {

                #region GetClientId

                case "GetClientId":

                    try
                    {
                        clientEntityReturn.IsSync = true;

                        clientEntityReturn.Action = action;
                        clientEntityReturn.ClientId = GPSTrackingDBV2Custom.Data.DataRepository.ClientsProvider.GetNextID();

                        //clientEntityReturn.ClientIdLocal = clientIdLocal;

                        clientEntityReturn.TransactionDate = ConvertDateFormatToISOString(transactionDate);
                        clientEntityReturn.Tick = TickManager.TickManager.GetTick(transactionDate).ToString();
                        clientEntityReturn.SyncTransaction = syncTransaction;

                        clientEntityReturn.TypeUserTransaction = typeUserTransaction;
                        clientEntityReturn.CompanyIdTransaction = companyIdTransaction;
                        clientEntityReturn.UsernameTransaction = usernameTransaction;
                        clientEntityReturn.UuidTransaction = uuidTransaction;
                        clientEntityReturn.Name = name;
                        clientEntityReturn.Latitude = latitude;
                        clientEntityReturn.Longitude = longitude;
                        clientEntityReturn.Phone1 = phone1;
                        clientEntityReturn.Phone2 = phone2;

                        clientEntitiesReturn.Add(clientEntityReturn);

                    }
                    catch (Exception ex)
                    {

                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Action = action;
                        clientEntityReturn.Message = ex.Message;
                        clientEntitiesReturn.Add(clientEntityReturn);
                    }

                    break;

                #endregion

                #region Insert

                case "Insert":

                    clientEntity = new GPSTrackingDBV2.Entities.Clients();
                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                    newTick = TickManager.TickManager.GetTick(transactionDate);

                    try
                    {
                        tm.BeginTransaction();

                        clientEntityReturn.Action = action;
                        clientEntityReturn.IsSync = true;

                        clientEntity.ClientId = clientId;
                        clientEntityReturn.ClientId = clientId;

                        clientEntityReturn.SyncTransaction = syncTransaction;

                        clientEntity.Name =  DecodingUrlValue(name);
                        clientEntityReturn.Name = clientEntity.Name;

                        clientEntity.Latitude = latitude;
                        clientEntityReturn.Latitude = latitude;

                        clientEntity.Longitude = longitude;
                        clientEntityReturn.Longitude = longitude;

                        clientEntity.Phone1 = DecodingUrlValue(phone1);
                        clientEntityReturn.Phone1 = clientEntity.Phone1;

                        clientEntity.Phone2 = DecodingUrlValue(phone2);
                        clientEntityReturn.Phone2 = clientEntity.Phone2;

                        clientEntity.LastTick = newTick;
                        clientEntityReturn.Tick = newTick.ToString();

                            
                        clientLogEntity = new GPSTrackingDBV2.Entities.ClientsLog();

                        clientLogEntity.ClientId = clientEntity.ClientId;

                        clientLogEntity.TransactionDate = transactionDate;

                        clientLogEntity.Tick = newTick;

                        clientLogEntity.SyncTransaction = syncTransaction;

                        clientLogEntity.Name = clientEntity.Name;

                        clientLogEntity.Phone1 = clientEntity.Phone1;

                        clientLogEntity.Phone2 = clientEntity.Phone2;

                        clientLogEntity.Latitude = clientEntity.Latitude;

                        clientLogEntity.Longitude = clientEntity.Longitude;

                        clientLogEntity.UuidTransaction = uuidTransaction;

                        clientLogEntity.CompanyIdTransaction = companyIdTransaction;

                        clientLogEntity.TypeUserTransaction = typeUserTransaction;

                        clientLogEntity.UsernameTransaction = usernameTransaction;

                        try
                        {
                            GPSTrackingDBV2.Data.DataRepository.ClientsProvider.Insert(tm, clientEntity);
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = ex.Message.ToUpper();
                            if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                            {
                                tm.Rollback();
                                clientEntityReturn.IsSync = false;
                                clientEntityReturn.Action = action;
                                clientEntityReturn.Message = ex.Message;
                                clientEntitiesReturn.Add(clientEntityReturn);
                                break;
                            }
                            clientEntityReturn.IsSync = true;
                            clientEntityReturn.Action = action;
                        }

                        try
                        {
                            GPSTrackingDBV2.Data.DataRepository.ClientsLogProvider.Insert(tm, clientLogEntity);
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = ex.Message.ToUpper();
                            if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                            {
                                tm.Rollback();
                                clientEntityReturn.IsSync = false;
                                clientEntityReturn.Action = action;
                                clientEntityReturn.Message = ex.Message;
                                clientEntitiesReturn.Add(clientEntityReturn);
                                break;
                            }
                            clientEntityReturn.IsSync = true;
                            clientEntityReturn.Action = action;
                        }
                            
                        GPSTrackingDBV2.Entities.ClientsGroupsByCompanies clientGroupByCompaniesEntity = GPSTrackingDBV2.Data.DataRepository.ClientsGroupsByCompaniesProvider.GetByCompanyIdClientGroupId(tm, companyIdTransaction, clientGroupId);

                        if (clientGroupByCompaniesEntity != null)
                        {
                            GPSTrackingDBV2.Entities.ClientsByClientsGroups clientsByClientsGroupsEntity = new ClientsByClientsGroups();

                            clientsByClientsGroupsEntity.ClientGroupId = clientGroupId;
                            clientsByClientsGroupsEntity.ClientId = clientId;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.ClientsByClientsGroupsProvider.Insert(tm, clientsByClientsGroupsEntity);
                            }
                            catch (Exception ex)
                            {
                                string errorMsg = ex.Message.ToUpper();
                                if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                                {
                                    tm.Rollback();
                                    clientEntityReturn.IsSync = false;
                                    clientEntityReturn.Action = action;
                                    clientEntityReturn.Message = ex.Message;
                                    clientEntitiesReturn.Add(clientEntityReturn);
                                    break;
                                }
                                clientEntityReturn.IsSync = true;
                                clientEntityReturn.Action = action;
                            }
                        }
                        else
                        {
                            GPSTrackingDBV2.Entities.TList<ClientsGroupsByCompanies> ClientsGroupsByCompaniesEntities = GPSTrackingDBV2.Data.DataRepository.ClientsGroupsByCompaniesProvider.GetByCompanyId(tm, companyIdTransaction);
                            GPSTrackingDBV2.Entities.ClientsByClientsGroups clientsByClientsGroupsEntity = new ClientsByClientsGroups();

                            if (ClientsGroupsByCompaniesEntities.Count > 0)
                            {
                                clientsByClientsGroupsEntity.ClientGroupId = ClientsGroupsByCompaniesEntities[0].ClientGroupId;
                                clientsByClientsGroupsEntity.ClientId = clientId;

                                try
                                {
                                    GPSTrackingDBV2.Data.DataRepository.ClientsByClientsGroupsProvider.Insert(tm, clientsByClientsGroupsEntity);
                                }
                                catch (Exception ex)
                                {
                                    string errorMsg = ex.Message.ToUpper();
                                    if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                                    {
                                        tm.Rollback();
                                        clientEntityReturn.IsSync = false;
                                        clientEntityReturn.Action = action;
                                        clientEntityReturn.Message = ex.Message;
                                        clientEntitiesReturn.Add(clientEntityReturn);
                                        break;
                                    }
                                    clientEntityReturn.IsSync = true;
                                    clientEntityReturn.Action = action;
                                }
                            }
                            else
                            {
                                int newClientGroupId;
                                GPSTrackingDBV2.Entities.ClientsGroups clientsGroupsEntity = new ClientsGroups();

                                newClientGroupId = GPSTrackingDBV2Custom.Data.DataRepository.ClientsGroupsProvider.GetNextID();

                                clientsGroupsEntity.ClientGroupId = newClientGroupId;
                                clientsGroupsEntity.Name = "Clientes Registrados con Dispositivos Móviles.";

                                GPSTrackingDBV2.Data.DataRepository.ClientsGroupsProvider.Insert(tm, clientsGroupsEntity);

                                clientsByClientsGroupsEntity.ClientId = clientId;
                                clientsByClientsGroupsEntity.ClientGroupId = newClientGroupId;
                                GPSTrackingDBV2.Data.DataRepository.ClientsByClientsGroupsProvider.Insert(tm, clientsByClientsGroupsEntity);
                            }
                        }
                        

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsLogByUuidProvider.UpdateSync(clientId, uuidTransaction, newTick, transactionDate))
                        {
                            clientsLogByUuidEntity = new ClientsLogByUuid();
                            try
                            {

                                clientsLogByUuidEntity.ClientId = clientId;
                                clientsLogByUuidEntity.TransactionDate = transactionDate;
                                clientsLogByUuidEntity.Tick = newTick;
                                clientsLogByUuidEntity.Uuid = uuidTransaction;
                                clientsLogByUuidEntity.IsSync = true;

                                GPSTrackingDBV2.Data.DataRepository.ClientsLogByUuidProvider.Insert(tm, clientsLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                tm.Rollback();
                                clientEntityReturn.IsSync = false;
                                clientEntityReturn.Message = "No se actualizó el regisro de log de cliente." + ex.Message;
                                break;
                            }
                        }

                      
                        clientEntitiesReturn.Add(clientEntityReturn);

                        tm.Commit();
                    }
                    catch (Exception ex)
                    {
                        tm.Rollback();
                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Action = action;
                        clientEntityReturn.Message = ex.Message;
                        clientEntitiesReturn.Add(clientEntityReturn);
                    }
                    break;

                #endregion

                #region InsertLog

                case "InsertLog":

                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
                    tm.BeginTransaction();
                    
                    try
                    {
                        clientLogEntity = new GPSTrackingDBV2.Entities.ClientsLog();

                        clientEntityReturn.IsSync = true;

                        clientEntityReturn.Action = action;

                        clientLogEntity.ClientId = clientId;
                        clientEntityReturn.ClientId = clientId;

                        clientLogEntity.TransactionDate = transactionDate;
                        clientEntityReturn.TransactionDate = ConvertDateFormatToISOString(transactionDate);

                        newTick = TickManager.TickManager.GetTick(transactionDate);

                        clientLogEntity.Tick = newTick;
                        clientEntityReturn.Tick = newTick.ToString();

                        clientLogEntity.SyncTransaction = syncTransaction;
                        clientEntityReturn.SyncTransaction = syncTransaction;

                        clientLogEntity.Name = DecodingUrlValue(name);
                        clientEntityReturn.Name = clientLogEntity.Name;

                        clientLogEntity.Phone1 = DecodingUrlValue(phone1);
                        clientEntityReturn.Phone1 = clientLogEntity.Phone1;

                        clientLogEntity.Phone2 = DecodingUrlValue(phone2);
                        clientEntityReturn.Phone2 = clientLogEntity.Phone2;

                        clientLogEntity.Latitude = latitude;
                        clientEntityReturn.Latitude = latitude;

                        clientLogEntity.Longitude = longitude;
                        clientEntityReturn.Longitude = longitude;

                        clientLogEntity.UuidTransaction = uuidTransaction;
                        clientEntityReturn.UuidTransaction = uuidTransaction;

                        clientLogEntity.CompanyIdTransaction = companyIdTransaction;
                        clientEntityReturn.CompanyIdTransaction = companyIdTransaction;

                        clientLogEntity.TypeUserTransaction = typeUserTransaction;
                        clientEntityReturn.TypeUserTransaction = typeUserTransaction;

                        clientLogEntity.UsernameTransaction = usernameTransaction;
                        clientEntityReturn.UsernameTransaction = usernameTransaction;



                        try
                        {
                            GPSTrackingDBV2.Data.DataRepository.ClientsLogProvider.Insert(tm, clientLogEntity);
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = ex.Message.ToUpper();
                            if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                            {
                                tm.Rollback();
                                clientEntityReturn.IsSync = false;
                                clientEntityReturn.Action = action;
                                clientEntityReturn.Message = ex.Message;
                                clientEntitiesReturn.Add(clientEntityReturn);
                                break;
                            }
                            clientEntityReturn.IsSync = true;
                            clientEntityReturn.Action = action;
                        }

                        GPSTrackingDBV2Custom.Data.DataRepository.ClientsProvider.UpdateIfIsNewerSync(tm, clientLogEntity.ClientId, clientLogEntity.Name, clientLogEntity.Phone1, clientLogEntity.Phone2, latitude, longitude, newTick);

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsLogByUuidProvider.UpdateSync(clientId, uuidTransaction, newTick, transactionDate))
                        {
                            clientsLogByUuidEntity = new ClientsLogByUuid();
                            try
                            {

                                clientsLogByUuidEntity.ClientId = clientId;
                                clientsLogByUuidEntity.TransactionDate = transactionDate;
                                clientsLogByUuidEntity.Tick = newTick;
                                clientsLogByUuidEntity.Uuid = uuidTransaction;
                                clientsLogByUuidEntity.IsSync = true;

                                GPSTrackingDBV2.Data.DataRepository.ClientsLogByUuidProvider.Insert(tm, clientsLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                tm.Rollback();
                                clientEntityReturn.IsSync = false;
                                clientEntityReturn.Message = "No se actualizó el regisro de log de cliente." + ex.Message;
                                break;
                            }
                        }



                        clientEntitiesReturn.Add(clientEntityReturn);

                        tm.Commit();
                    }
                    catch (Exception ex) {
                        tm.Rollback();
                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Action = action;
                        clientEntityReturn.Message = ex.Message;
                        clientEntitiesReturn.Add(clientEntityReturn);
                        break;
                    }
                    break;

                #endregion

                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.ClientsLogByUuidProvider.GetToSync(uuidTransaction, companyIdTransaction);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                clientEntityReturn = new Entities.Clients();

                                clientEntityReturn.Action = action;
                                clientEntityReturn.Total = total;

                                clientEntityReturn.ClientId = int.Parse(row["ClientID"].ToString());
                                clientEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                clientEntityReturn.Tick = row["Tick"].ToString();
                                clientEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                clientEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                clientEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                clientEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                clientEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();
                                clientEntityReturn.Name = row["Name"].ToString();
                                clientEntityReturn.Latitude = float.Parse(row["Latitude"].ToString());
                                clientEntityReturn.Longitude = float.Parse(row["Longitude"].ToString());
                                clientEntityReturn.Phone1 = row["Phone1"].ToString();
                                clientEntityReturn.Phone2 = row["Phone2"].ToString();
                                clientEntityReturn.IsSync = true;

                                clientEntitiesReturn.Add(clientEntityReturn);
                            }
                        }
                        else
                        {
                            clientEntityReturn.Action = action;
                            clientEntityReturn.Total = total;
                            clientEntityReturn.IsSync = true;
                            clientEntitiesReturn.Add(clientEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        clientEntitiesReturn.Clear();
                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Action = action;
                        clientEntityReturn.Message = ex.Message;
                        clientEntitiesReturn.Add(clientEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.ClientsLogByUuidProvider.GetToSync(uuidTransaction, companyIdTransaction);

                        clientEntityReturn.Total = dt.Rows.Count;
                        clientEntityReturn.IsSync = true;
                        clientEntityReturn.Action = action;
                        clientEntitiesReturn.Add(clientEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Action = action;
                        clientEntityReturn.Message = ex.Message;
                        clientEntitiesReturn.Add(clientEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        clientEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsLogByUuidProvider.UpdateSync(clientId, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            clientsLogByUuidEntity = new ClientsLogByUuid();

                            clientsLogByUuidEntity.ClientId = clientId;
                            clientsLogByUuidEntity.TransactionDate = transactionDate;
                            clientsLogByUuidEntity.Tick = Int64.Parse(tick);
                            clientsLogByUuidEntity.Uuid = uuidTransaction;
                            clientsLogByUuidEntity.IsSync = true;

                            clientEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.ClientsLogByUuidProvider.Insert(clientsLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                clientEntityReturn.IsSync = false;
                                clientEntityReturn.Message = "No se actualizó el regisro de log de cliente." + ex.Message;
                            }
                        }
                        else
                        {
                            clientEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Action = action;
                        clientEntityReturn.Message = ex.Message;
                    }
                    clientEntitiesReturn.Add(clientEntityReturn);

                    break;
                #endregion

                #region UpdateClients

                case "UpdateClients":

                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                    try
                    {
                        clientEntityReturn.Action = action;
                        clientEntityReturn.IsSync = true;

                        tm.BeginTransaction();

                        GPSTrackingDBV2Custom.Data.DataRepository.ClientsProvider.UpdateIfIsNewerSync(tm, clientId, name, phone1, phone2, latitude, longitude, Int64.Parse(tick));

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsLogByUuidProvider.UpdateSync(clientId, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            clientsLogByUuidEntity = new ClientsLogByUuid();

                            clientsLogByUuidEntity.ClientId = clientId;
                            clientsLogByUuidEntity.TransactionDate = transactionDate;
                            clientsLogByUuidEntity.Tick = Int64.Parse(tick);
                            clientsLogByUuidEntity.Uuid = uuidTransaction;
                            clientsLogByUuidEntity.IsSync = true;

                            GPSTrackingDBV2.Data.DataRepository.ClientsLogByUuidProvider.Insert(tm, clientsLogByUuidEntity);
                        }

                        tm.Commit();

                    }
                    catch (Exception ex)
                    {
                        tm.Rollback();
                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Message = "No se actualizó el cliente." + ex.Message;
                    }

                    clientEntitiesReturn.Add(clientEntityReturn);

                    break;

                #endregion

                #region DeleteClients

                case "DeleteClients":

                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                    try
                    {
                        clientEntityReturn.Action = action;
                        clientEntityReturn.IsSync = true;


                        GPSTrackingDBV2Custom.Data.DataRepository.ClientsProvider.DeleteSync(tm, clientGroupId, clientId);

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsLogByUuidProvider.UpdateSync(clientId, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            clientsLogByUuidEntity = new ClientsLogByUuid();

                            clientsLogByUuidEntity.ClientId = clientId;
                            clientsLogByUuidEntity.TransactionDate = transactionDate;
                            clientsLogByUuidEntity.Tick = Int64.Parse(tick);
                            clientsLogByUuidEntity.Uuid = uuidTransaction;
                            clientsLogByUuidEntity.IsSync = true;

                            GPSTrackingDBV2.Data.DataRepository.ClientsLogByUuidProvider.Insert(tm, clientsLogByUuidEntity);
                        }

                    }
                    catch (Exception ex)
                    {
                        tm.Rollback();
                        clientEntityReturn.IsSync = false;
                        clientEntityReturn.Message = "No se eliminó el cliente." + ex.Message;
                    }

                    clientEntitiesReturn.Add(clientEntityReturn);

                    break;

                #endregion
            }

            return clientEntitiesReturn;

        }
        
        public List<Entities.ClientsByEmail> SyncClientsByEmail(string action, string syncTransaction, string tick, int clientId, int emailId, string name, string email, DateTime transactionDate, string typeUserTransaction, string usernameTransaction, string uuidTransaction, int companyIdTransaction)
        {
            Entities.ClientsByEmail clientsByEmailEntityReturn = new Entities.ClientsByEmail();
            List<Entities.ClientsByEmail> clientsByEmailEntitiesReturn = new List<Entities.ClientsByEmail>();

            GPSTrackingDBV2.Data.TransactionManager tm;
            GPSTrackingDBV2.Entities.ClientsByEmail clientsByEmailEntity;
            GPSTrackingDBV2.Entities.ClientsByEmailLog clientsByEmailLogEntity;
            GPSTrackingDBV2.Entities.ClientsByEmailLogByUuid clientsByEmailLogByUuidEntity;
            long newTick;

            switch (action)
            {

                #region Insert

                case "Insert":

                    clientsByEmailEntity = new GPSTrackingDBV2.Entities.ClientsByEmail();
                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                    newTick = TickManager.TickManager.GetTick(transactionDate);

                    try
                    {
                        tm.BeginTransaction();

                        clientsByEmailEntityReturn.Action = action;
                        clientsByEmailEntityReturn.IsSync = true;

                        clientsByEmailEntity.ClientId = clientId;
                        clientsByEmailEntityReturn.ClientId = clientsByEmailEntity.ClientId;

                        clientsByEmailEntityReturn.SyncTransaction = syncTransaction;

                        clientsByEmailEntity.Name = DecodingUrlValue(name);
                        clientsByEmailEntityReturn.Name = clientsByEmailEntity.Name;

                        clientsByEmailEntity.Email = DecodingUrlValue(email);
                        clientsByEmailEntityReturn.Email = clientsByEmailEntity.Email;

                        clientsByEmailEntity.LastTick = newTick;
                        clientsByEmailEntityReturn.Tick = newTick.ToString();
                        
                        clientsByEmailLogEntity = new GPSTrackingDBV2.Entities.ClientsByEmailLog();

                        clientsByEmailLogEntity.ClientId = clientsByEmailEntity.ClientId;

                        clientsByEmailLogEntity.TransactionDate = transactionDate;

                        clientsByEmailLogEntity.Tick = newTick;

                        clientsByEmailLogEntity.SyncTransaction = syncTransaction;

                        clientsByEmailLogEntity.Name = clientsByEmailEntity.Name;

                        clientsByEmailLogEntity.Email = clientsByEmailEntity.Email;

                        clientsByEmailLogEntity.UuidTransaction = uuidTransaction;

                        clientsByEmailLogEntity.CompanyIdTransaction = companyIdTransaction;

                        clientsByEmailLogEntity.TypeUserTransaction = typeUserTransaction;

                        clientsByEmailLogEntity.UsernameTransaction = usernameTransaction;

                        try
                        {
                            clientsByEmailEntity.EmailId = GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailProvider.Exists(clientsByEmailEntity.ClientId, clientsByEmailEntity.Name, clientsByEmailEntity.Email);
                            clientsByEmailLogEntity.EmailId = clientsByEmailEntity.EmailId;
                            clientsByEmailEntityReturn.EmailId = clientsByEmailEntity.EmailId;

                            if (clientsByEmailEntity.EmailId == -1)
                            {
                                clientsByEmailEntity.EmailId = GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailProvider.GetNextID(clientId);
                                clientsByEmailLogEntity.EmailId = clientsByEmailEntity.EmailId;
                                clientsByEmailEntityReturn.EmailId = clientsByEmailEntity.EmailId;
                                GPSTrackingDBV2.Data.DataRepository.ClientsByEmailProvider.Insert(tm, clientsByEmailEntity);
                            }

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.ClientsByEmailLogProvider.Insert(tm, clientsByEmailLogEntity);
                            }
                            catch (Exception ex)
                            {
                                string errorMsg = ex.Message.ToUpper();
                                if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                                {
                                    tm.Rollback();
                                    clientsByEmailEntityReturn.IsSync = false;
                                    clientsByEmailEntityReturn.Action = action;
                                    clientsByEmailEntityReturn.Message = ex.Message;
                                    clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                                    break;
                                }
                                clientsByEmailEntityReturn.IsSync = true;
                                clientsByEmailEntityReturn.Action = action;
                            }

                        }
                        catch (Exception ex)
                        {
                            
                            tm.Rollback();
                            clientsByEmailEntityReturn.IsSync = false;
                            clientsByEmailEntityReturn.Action = action;
                            clientsByEmailEntityReturn.Message = ex.Message;
                            clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                            break;
                            
                        }

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailLogByUuidProvider.UpdateSync(clientsByEmailEntity.ClientId, clientsByEmailEntity.EmailId, uuidTransaction, newTick, transactionDate))
                        {
                            clientsByEmailLogByUuidEntity = new ClientsByEmailLogByUuid();
                            try
                            {

                                clientsByEmailLogByUuidEntity.ClientId = clientId;
                                clientsByEmailLogByUuidEntity.EmailId = clientsByEmailLogEntity.EmailId;
                                clientsByEmailLogByUuidEntity.TransactionDate = transactionDate;
                                clientsByEmailLogByUuidEntity.Tick = newTick;
                                clientsByEmailLogByUuidEntity.Uuid = uuidTransaction;
                                clientsByEmailLogByUuidEntity.IsSync = true;

                                clientsByEmailEntityReturn.IsSync = true;

                                GPSTrackingDBV2.Data.DataRepository.ClientsByEmailLogByUuidProvider.Insert(tm, clientsByEmailLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                tm.Rollback();
                                clientsByEmailEntityReturn.IsSync = false;
                                clientsByEmailEntityReturn.Message = "No se actualizó el regisro de log del correo del cliente." + ex.Message;
                                clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                                break;
                            }
                        }


                        clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);

                        tm.Commit();
                    }
                    catch (Exception ex)
                    {
                        tm.Rollback();
                        clientsByEmailEntityReturn.IsSync = false;
                        clientsByEmailEntityReturn.Action = action;
                        clientsByEmailEntityReturn.Message = ex.Message;
                        clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                    }
                    break;

                #endregion

                #region InsertLog

                case "InsertLog":

                    clientsByEmailLogEntity = new GPSTrackingDBV2.Entities.ClientsByEmailLog();

                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                    clientsByEmailEntityReturn.IsSync = true;

                    clientsByEmailEntityReturn.Action = action;

                    clientsByEmailLogEntity.ClientId = clientId;
                    clientsByEmailEntityReturn.ClientId = clientId;

                    clientsByEmailLogEntity.EmailId = emailId;
                    clientsByEmailEntityReturn.EmailId = emailId;


                    clientsByEmailLogEntity.TransactionDate = transactionDate;
                    clientsByEmailEntityReturn.TransactionDate = ConvertDateFormatToISOString(transactionDate);

                    newTick = TickManager.TickManager.GetTick(transactionDate);

                    clientsByEmailLogEntity.Tick = newTick;
                    clientsByEmailEntityReturn.Tick = newTick.ToString();

                    clientsByEmailLogEntity.SyncTransaction = syncTransaction;
                    clientsByEmailEntityReturn.SyncTransaction = syncTransaction;

                    clientsByEmailLogEntity.Name = DecodingUrlValue(name);
                    clientsByEmailEntityReturn.Name = clientsByEmailLogEntity.Name;

                    clientsByEmailLogEntity.Email = DecodingUrlValue(email);
                    clientsByEmailEntityReturn.Email = clientsByEmailLogEntity.Email;

                    clientsByEmailLogEntity.UuidTransaction = uuidTransaction;
                    clientsByEmailEntityReturn.UuidTransaction = uuidTransaction;

                    clientsByEmailLogEntity.CompanyIdTransaction = companyIdTransaction;
                    clientsByEmailEntityReturn.CompanyIdTransaction = companyIdTransaction;

                    clientsByEmailLogEntity.TypeUserTransaction = typeUserTransaction;
                    clientsByEmailEntityReturn.TypeUserTransaction = typeUserTransaction;

                    clientsByEmailLogEntity.UsernameTransaction = usernameTransaction;
                    clientsByEmailEntityReturn.UsernameTransaction = usernameTransaction;

                    try
                    {
                        tm.BeginTransaction();
                        GPSTrackingDBV2.Data.DataRepository.ClientsByEmailLogProvider.Insert(tm, clientsByEmailLogEntity);
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = ex.Message.ToUpper();
                        if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                        {
                            tm.Rollback();
                            clientsByEmailEntityReturn.IsSync = false;
                            clientsByEmailEntityReturn.Action = action;
                            clientsByEmailEntityReturn.Message = ex.Message;
                            clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                            break;
                        }
                        clientsByEmailEntityReturn.IsSync = true;
                        clientsByEmailEntityReturn.Action = action;
                    }

                    GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailProvider.UpdateIfIsNewerSync(tm, clientId, emailId, clientsByEmailLogEntity.Name, clientsByEmailLogEntity.Email, newTick);

                    if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailLogByUuidProvider.UpdateSync(clientId, emailId, uuidTransaction, newTick, transactionDate))
                    {
                        clientsByEmailLogByUuidEntity = new ClientsByEmailLogByUuid();
                        try
                        {

                            clientsByEmailLogByUuidEntity.ClientId = clientId;
                            clientsByEmailLogByUuidEntity.EmailId = emailId;
                            clientsByEmailLogByUuidEntity.TransactionDate = transactionDate;
                            clientsByEmailLogByUuidEntity.Tick = newTick;
                            clientsByEmailLogByUuidEntity.Uuid = uuidTransaction;
                            clientsByEmailLogByUuidEntity.IsSync = true;
                            
                            clientsByEmailEntityReturn.IsSync = true;

                            GPSTrackingDBV2.Data.DataRepository.ClientsByEmailLogByUuidProvider.Insert(tm, clientsByEmailLogByUuidEntity);
                        }
                        catch (Exception ex)
                        {
                            tm.Rollback();
                            clientsByEmailEntityReturn.IsSync = false;
                            clientsByEmailEntityReturn.Message = "No se actualizó el regisro de log de correos de clientes." + ex.Message;
                            clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                            break;
                        }
                    }

                    tm.Commit();

                    clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);

                    break;

                #endregion

                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailLogByUuidProvider.GetToSync(uuidTransaction, companyIdTransaction);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                clientsByEmailEntityReturn = new Entities.ClientsByEmail();

                                clientsByEmailEntityReturn.Action = action;
                                clientsByEmailEntityReturn.Total = total;

                                clientsByEmailEntityReturn.ClientId = int.Parse(row["ClientID"].ToString());
                                clientsByEmailEntityReturn.EmailId = int.Parse(row["EmailID"].ToString());
                                clientsByEmailEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                clientsByEmailEntityReturn.Tick = row["Tick"].ToString();
                                clientsByEmailEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                clientsByEmailEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                clientsByEmailEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                clientsByEmailEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                clientsByEmailEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();
                                clientsByEmailEntityReturn.Name = row["Name"].ToString();
                                clientsByEmailEntityReturn.Email = row["Email"].ToString();
                                clientsByEmailEntityReturn.IsSync = true;

                                clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                            }
                        }
                        else
                        {
                            clientsByEmailEntityReturn.Action = action;
                            clientsByEmailEntityReturn.Total = total;
                            clientsByEmailEntityReturn.IsSync = true;
                            clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        clientsByEmailEntitiesReturn.Clear();
                        clientsByEmailEntityReturn.IsSync = false;
                        clientsByEmailEntityReturn.Action = action;
                        clientsByEmailEntityReturn.Message = ex.Message;
                        clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailLogByUuidProvider.GetToSync(uuidTransaction, companyIdTransaction);

                        clientsByEmailEntityReturn.Total = dt.Rows.Count;
                        clientsByEmailEntityReturn.IsSync = true;
                        clientsByEmailEntityReturn.Action = action;
                        clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        clientsByEmailEntityReturn.IsSync = false;
                        clientsByEmailEntityReturn.Action = action;
                        clientsByEmailEntityReturn.Message = ex.Message;
                        clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        clientsByEmailEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.ClientsByEmailLogByUuidProvider.UpdateSync(clientId, emailId, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            clientsByEmailLogByUuidEntity = new ClientsByEmailLogByUuid();

                            clientsByEmailLogByUuidEntity.ClientId = clientId;
                            clientsByEmailLogByUuidEntity.EmailId = emailId;
                            clientsByEmailLogByUuidEntity.TransactionDate = transactionDate;
                            clientsByEmailLogByUuidEntity.Tick = Int64.Parse(tick);
                            clientsByEmailLogByUuidEntity.Uuid = uuidTransaction;
                            clientsByEmailLogByUuidEntity.IsSync = true;

                            clientsByEmailEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.ClientsByEmailLogByUuidProvider.Insert(clientsByEmailLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                clientsByEmailEntityReturn.IsSync = false;
                                clientsByEmailEntityReturn.Message = "No se actualizó el regisro de log de correos de cliente." + ex.Message;
                            }
                        }
                        else
                        {
                            clientsByEmailEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        clientsByEmailEntityReturn.IsSync = false;
                        clientsByEmailEntityReturn.Action = action;
                        clientsByEmailEntityReturn.Message = ex.Message;
                    }
                    clientsByEmailEntitiesReturn.Add(clientsByEmailEntityReturn);

                    break;
                #endregion

            }

            return clientsByEmailEntitiesReturn;

        }

        public Entities.EmailToSendStock SyncEmailToSendStock(string action, int emailToSendStockId, int stockId, int stockFileId, int clientId, DateTime creationDate, string typeUserTransaction, string usernameTransaction, string uuidTransaction, int companyId, int reservedQuantity, bool isSendInvoice)
        {
            Entities.EmailToSendStock emailToSendStockEntityReturn = new Entities.EmailToSendStock();

            EntityFrameworkManager.EmailToSendStocks emailToSendStocksEntity;
            GPSTrackingDBV2.Entities.EmailToSendStockByClients emailToSendStockByClientsEntity;
            GPSTrackingDBV2.Entities.EmailToSendStockByStockFiles emailToSendStockByStockFilesEntity;

            switch (action)
            {

                #region GetEmailToSendStockId

                case "GetEmailToSendStockId":

                    try
                    {
                        emailToSendStockEntityReturn.IsSync = true;

                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.EmailToSendStockId = GPSTrackingDBV2Custom.Data.DataRepository.EmailToSendStocksProvider.GetNextID(companyId);

                    }
                    catch (Exception ex)
                    {

                        emailToSendStockEntityReturn.IsSync = false;
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.Message = ex.Message;
                    }

                    break;

                #endregion

                #region InsertEmailToSendStock

                case "InsertEmailToSendStock":

                    emailToSendStocksEntity = new EntityFrameworkManager.EmailToSendStocks();

                    try
                    {
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.IsSync = true;

                        emailToSendStocksEntity.EmailToSendStockID = emailToSendStockId;
                        emailToSendStocksEntity.StatusID = "SYN";
                        emailToSendStockEntityReturn.EmailToSendStockId = emailToSendStockId;

                        emailToSendStocksEntity.CompanyID = companyId;
                        emailToSendStockEntityReturn.CompanyId = companyId;

                        emailToSendStocksEntity.TypeUserTransaction = typeUserTransaction;
                        emailToSendStocksEntity.UuidTransaction = uuidTransaction;
                        emailToSendStocksEntity.UsernameTransaction = usernameTransaction;
                        emailToSendStocksEntity.CreationDate = creationDate;
                        emailToSendStocksEntity.IsSendInvoice = isSendInvoice;

                        try
                        {
                            using (var falconSystemDBProvider = new EntityFrameworkManager.FalconSystemDBEntities())
                            {
                                falconSystemDBProvider.EmailToSendStocks.Add(emailToSendStocksEntity);
                                falconSystemDBProvider.SaveChanges();
                            }
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = ex.Message.ToUpper();
                            if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                            {
                                emailToSendStockEntityReturn.IsSync = false;
                                emailToSendStockEntityReturn.Action = action;
                                emailToSendStockEntityReturn.Message = ex.Message;
                                break;
                            }
                            emailToSendStockEntityReturn.IsSync = true;
                            emailToSendStockEntityReturn.Action = action;
                        }

                    }
                    catch (Exception ex)
                    {
                        emailToSendStockEntityReturn.IsSync = false;
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.Message = ex.Message;
                    }
                    break;

                #endregion

                #region InsertEmailToSendStockByClients

                case "InsertEmailToSendStockByClients":

                    emailToSendStockByClientsEntity = new GPSTrackingDBV2.Entities.EmailToSendStockByClients();

                    try
                    {
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.IsSync = true;

                        emailToSendStockByClientsEntity.EmailToSendStockId = emailToSendStockId;
                        emailToSendStockEntityReturn.EmailToSendStockId = emailToSendStockId;

                        emailToSendStockByClientsEntity.CompanyId = companyId;
                        emailToSendStockEntityReturn.CompanyId = companyId;

                        emailToSendStockByClientsEntity.ClientId = clientId;
                        emailToSendStockEntityReturn.ClientId = clientId;

                        try
                        {
                            GPSTrackingDBV2.Data.DataRepository.EmailToSendStockByClientsProvider.Insert(emailToSendStockByClientsEntity);
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = ex.Message.ToUpper();
                            if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                            {
                                emailToSendStockEntityReturn.IsSync = false;
                                emailToSendStockEntityReturn.Action = action;
                                emailToSendStockEntityReturn.Message = ex.Message;
                                break;
                            }
                            emailToSendStockEntityReturn.IsSync = true;
                            emailToSendStockEntityReturn.Action = action;
                        }

                    }
                    catch (Exception ex)
                    {
                        emailToSendStockEntityReturn.IsSync = false;
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.Message = ex.Message;
                    }
                    break;

                #endregion

                #region InsertEmailToSendStockByStocks

                case "InsertEmailToSendStockByStocks":

                    try
                    {
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.IsSync = true;

                        emailToSendStockEntityReturn.EmailToSendStockId = emailToSendStockId;

                        emailToSendStockEntityReturn.CompanyId = companyId;

                        emailToSendStockEntityReturn.StockId = stockId;

                        emailToSendStockEntityReturn.ReservedQuantity = reservedQuantity;

                        try
                        {
                            GPSTrackingDBV2Custom.Data.DataRepository.EmailToSendStockByStocksProvider.Insert(emailToSendStockId, companyId, stockId, reservedQuantity);
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = ex.Message.ToUpper();
                            if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                            {
                                emailToSendStockEntityReturn.IsSync = false;
                                emailToSendStockEntityReturn.Action = action;
                                emailToSendStockEntityReturn.Message = ex.Message;
                                break;
                            }
                            emailToSendStockEntityReturn.IsSync = true;
                            emailToSendStockEntityReturn.Action = action;
                        }

                    }
                    catch (Exception ex)
                    {
                        emailToSendStockEntityReturn.IsSync = false;
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.Message = ex.Message;
                    }
                    break;

                #endregion

                #region InsertEmailToSendStockByStockFiles

                case "InsertEmailToSendStockByStockFiles":

                    emailToSendStockByStockFilesEntity = new GPSTrackingDBV2.Entities.EmailToSendStockByStockFiles();

                    try
                    {
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.IsSync = true;

                        emailToSendStockByStockFilesEntity.EmailToSendStockId = emailToSendStockId;
                        emailToSendStockEntityReturn.EmailToSendStockId = emailToSendStockId;

                        emailToSendStockByStockFilesEntity.CompanyId = companyId;
                        emailToSendStockEntityReturn.CompanyId = companyId;

                        emailToSendStockByStockFilesEntity.StockFileId = stockFileId;
                        emailToSendStockEntityReturn.StockFileId = stockFileId;

                        try
                        {
                            GPSTrackingDBV2.Data.DataRepository.EmailToSendStockByStockFilesProvider.Insert(emailToSendStockByStockFilesEntity);
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = ex.Message.ToUpper();
                            if (!errorMsg.Contains("VIOLATION OF PRIMARY KEY"))
                            {
                                emailToSendStockEntityReturn.IsSync = false;
                                emailToSendStockEntityReturn.Action = action;
                                emailToSendStockEntityReturn.Message = ex.Message;
                                break;
                            }
                            emailToSendStockEntityReturn.IsSync = true;
                            emailToSendStockEntityReturn.Action = action;
                        }

                    }
                    catch (Exception ex)
                    {
                        emailToSendStockEntityReturn.IsSync = false;
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.Message = ex.Message;
                    }
                    break;

                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        emailToSendStockEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.EmailToSendStocksProvider.UpdateSync(companyId, emailToSendStockId))
                        {
                            emailToSendStockEntityReturn.IsSync = false;
                            emailToSendStockEntityReturn.Message = "No se pudo finalizar la sincronización de la solicitud de email";
                        }
                        else
                        {
                            emailToSendStockEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        emailToSendStockEntityReturn.IsSync = false;
                        emailToSendStockEntityReturn.Action = action;
                        emailToSendStockEntityReturn.Message = ex.Message;
                    }

                    break;
                #endregion

            }

            return emailToSendStockEntityReturn;

        }

        public List<Entities.Users> SyncUser(string action, string username, string tick, DateTime transactionDate, string uuid, int companyId)
        {
            Entities.Users usersEntityReturn = new Entities.Users();
            List<Entities.Users> usersEntitiesReturn = new List<Entities.Users>();

            GPSTrackingDBV2.Data.TransactionManager tm;
            GPSTrackingDBV2.Entities.Users usersEntity;
            GPSTrackingDBV2.Entities.UsersLog usersLogEntity;
            GPSTrackingDBV2.Entities.UsersLogByUuid usersLogByUuidEntity;

            switch (action)
            {
                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.UsersLogByUuidProvider.GetToSync(uuid, companyId);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                usersEntityReturn = new Entities.Users();

                                usersEntityReturn.Action = action;
                                usersEntityReturn.Total = total;

                                usersEntityReturn.Username = row["Username"].ToString();
                                usersEntityReturn.CompanyId = int.Parse(row["CompanyID"].ToString());
                                usersEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                usersEntityReturn.Tick = row["Tick"].ToString();
                                usersEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                usersEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                usersEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                usersEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                usersEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();
                                usersEntityReturn.Password = row["Password"].ToString();
                                usersEntityReturn.Identification = row["Identification"].ToString();
                                usersEntityReturn.Name = row["Name"].ToString();
                                usersEntityReturn.FirstName = row["FirstName"].ToString();
                                usersEntityReturn.LastName = row["LastName"].ToString();
                                usersEntityReturn.CountryId = int.Parse(row["CountryId"].ToString());
                                usersEntityReturn.StateId = int.Parse(row["StateId"].ToString());
                                usersEntityReturn.Mobile = row["Mobile"].ToString();
                                usersEntityReturn.Phone = row["Phone"].ToString();
                                usersEntityReturn.IsActive = bool.Parse(row["IsActive"].ToString());
                                usersEntityReturn.Email = row["Email"].ToString();

                                usersEntityReturn.IsSync = true;

                                usersEntitiesReturn.Add(usersEntityReturn);
                            }
                        }
                        else
                        {
                            usersEntityReturn.Action = action;
                            usersEntityReturn.Total = total;
                            usersEntityReturn.IsSync = true;
                            usersEntitiesReturn.Add(usersEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        usersEntitiesReturn.Clear();
                        usersEntityReturn.IsSync = false;
                        usersEntityReturn.Action = action;
                        usersEntityReturn.Message = ex.Message;
                        usersEntitiesReturn.Add(usersEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.UsersLogByUuidProvider.GetToSync(uuid, companyId);

                        usersEntityReturn.Total = dt.Rows.Count;
                        usersEntityReturn.IsSync = true;
                        usersEntityReturn.Action = action;
                        usersEntitiesReturn.Add(usersEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        usersEntityReturn.IsSync = false;
                        usersEntityReturn.Action = action;
                        usersEntityReturn.Message = ex.Message;
                        usersEntitiesReturn.Add(usersEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        usersEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.UsersLogByUuidProvider.UpdateSync(companyId, username, uuid, Int64.Parse(tick), transactionDate))
                        {
                            usersLogByUuidEntity = new UsersLogByUuid();

                            usersLogByUuidEntity.Username = username;
                            usersLogByUuidEntity.CompanyId = companyId;
                            usersLogByUuidEntity.TransactionDate = transactionDate;
                            usersLogByUuidEntity.Tick = Int64.Parse(tick);
                            usersLogByUuidEntity.Uuid = uuid;
                            usersLogByUuidEntity.IsSync = true;

                            usersEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.UsersLogByUuidProvider.Insert(usersLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                usersEntityReturn.IsSync = false;
                                usersEntityReturn.Message = "No se actualizó el regisro de log de cliente." + ex.Message;
                            }
                        }
                        else
                        {
                            usersEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        usersEntityReturn.IsSync = false;
                        usersEntityReturn.Action = action;
                        usersEntityReturn.Message = ex.Message;
                    }
                    usersEntitiesReturn.Add(usersEntityReturn);

                    break;
                #endregion
            }

            return usersEntitiesReturn;

        }

        public List<Entities.Stock> SyncStock(string action, int stockId, int companyId, DateTime transactionDate, string tick, string uuidTransaction, string adminUsername, int totalToGet)
        {
            Entities.Stock stockEntityReturn = new Entities.Stock();
            List<Entities.Stock> stockEntitiesReturn = new List<Entities.Stock>();

            GPSTrackingDBV2.Data.TransactionManager tm;

            GPSTrackingDBV2.Entities.StockLogByUuid stockLogByUuidEntity;


            switch (action)
            {
                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockLogByUuidProvider.GetToSync(uuidTransaction, companyId, totalToGet);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                stockEntityReturn = new Entities.Stock();

                                stockEntityReturn.Action = action;
                                stockEntityReturn.Total = total;

                                stockEntityReturn.StockId = int.Parse(row["StockID"].ToString());
                                stockEntityReturn.StockCode = row["StockCode"].ToString();
                                stockEntityReturn.StockBarCode = row["StockBarCode"].ToString();
                                stockEntityReturn.CompanyId = int.Parse(row["CompanyID"].ToString());
                                stockEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                stockEntityReturn.Tick = row["Tick"].ToString();
                                stockEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                stockEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                stockEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                stockEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                stockEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();
                                stockEntityReturn.Name = row["Name"].ToString();
                                stockEntityReturn.Description = row["Description"].ToString();
                                stockEntityReturn.PromotionalNote = row["PromotionalNote"].ToString();
                                stockEntityReturn.Brand = row["Brand"].ToString();
                                stockEntityReturn.UnitStock = row["UnitStock"].ToString();
                                stockEntityReturn.UnitStockByBox = row["UnitStockByBox"].ToString();
                                stockEntityReturn.Price = Decimal.Parse(row["Price"].ToString());
                                stockEntityReturn.Quantity = int.Parse(row["Quantity"].ToString());
                                stockEntityReturn.MinQuantity = int.Parse(row["MinQuantity"].ToString());
                                stockEntityReturn.ReservedQuantity = int.Parse(row["ReservedQuantity"].ToString());
                                stockEntityReturn.StockCategoryId = int.Parse(row["StockCategoryId"].ToString());
                                stockEntityReturn.ImageUrl = row["ImageUrl"].ToString();
                                stockEntityReturn.PDFDetailUrl = row["PDFDetailUrl"].ToString();
                                stockEntityReturn.VideoUrl = row["VideoUrl"].ToString();
                                stockEntityReturn.VideoThumbnailUrl = row["VideoThumbnailUrl"].ToString();

                                stockEntityReturn.IsSync = true;

                                stockEntitiesReturn.Add(stockEntityReturn);
                            }
                        }
                        else
                        {
                            stockEntityReturn.Action = action;
                            stockEntityReturn.Total = total;
                            stockEntityReturn.IsSync = true;
                            stockEntitiesReturn.Add(stockEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockEntitiesReturn.Clear();
                        stockEntityReturn.IsSync = false;
                        stockEntityReturn.Action = action;
                        stockEntityReturn.Message = ex.Message;
                        stockEntitiesReturn.Add(stockEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        stockEntityReturn.Total = GPSTrackingDBV2Custom.Data.DataRepository.StockLogByUuidProvider.GetTotalToSync(uuidTransaction, companyId);
                        stockEntityReturn.IsSync = true;
                        stockEntityReturn.Action = action;
                        stockEntitiesReturn.Add(stockEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        stockEntityReturn.IsSync = false;
                        stockEntityReturn.Action = action;
                        stockEntityReturn.Message = ex.Message;
                        stockEntitiesReturn.Add(stockEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        stockEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.StockLogByUuidProvider.UpdateSync(companyId, stockId, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            stockLogByUuidEntity = new StockLogByUuid();

                            stockLogByUuidEntity.StockId = stockId;
                            stockLogByUuidEntity.CompanyId = companyId;
                            stockLogByUuidEntity.TransactionDate = transactionDate;
                            stockLogByUuidEntity.Tick = Int64.Parse(tick);
                            stockLogByUuidEntity.Uuid = uuidTransaction;
                            stockLogByUuidEntity.IsSync = true;

                            stockEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.StockLogByUuidProvider.Insert(stockLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                stockEntityReturn.IsSync = false;
                                stockEntityReturn.Message = "No se actualizó el regisro de log del producto." + ex.Message;
                            }
                        }
                        else
                        {
                            stockEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        stockEntityReturn.IsSync = false;
                        stockEntityReturn.Action = action;
                        stockEntityReturn.Message = ex.Message;
                    }
                    stockEntitiesReturn.Add(stockEntityReturn);

                    break;
                #endregion

                #region "DeleteAllByStockId"

                case "DeleteAllByStockId":
                    
                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
                    stockEntityReturn = new Entities.Stock();
                    stockEntityReturn.IsSync = true;
                    try
                    {
                        tm.BeginTransaction();

                        GPSTrackingDBV2.Entities.Stock stockEntity;
                        GPSTrackingDBV2.Entities.StockLog stockLogEntity = new GPSTrackingDBV2.Entities.StockLog();
                        TList<GPSTrackingDBV2.Entities.StockByAditionalImages> stockByAditionalImagesEntities;
                        GPSTrackingDBV2.Entities.StockByAditionalImagesLog stockByAditionalImagesLog;
                        StockFilesManagerService.StockFilesManagerServiceClient stockFilesManagerServiceClient = new StockFilesManagerService.StockFilesManagerServiceClient();

                        Int64 newTick = TickManager.TickManager.GetTick(transactionDate);
                        string typeUserTransaction = "A";
                                                
                        stockEntity = GPSTrackingDBV2.Data.DataRepository.StockProvider.GetByCompanyIdStockId(companyId, stockId);
                        
                        if (stockEntity != null)
                        {
                           
                            stockByAditionalImagesEntities = GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesProvider.GetByCompanyIdStockId(companyId, stockId);

                            foreach (GPSTrackingDBV2.Entities.StockByAditionalImages stockByAditionalImages in stockByAditionalImagesEntities)
                            {
                                stockByAditionalImagesLog = new GPSTrackingDBV2.Entities.StockByAditionalImagesLog();

                                stockByAditionalImagesLog.CompanyId = stockByAditionalImages.CompanyId;
                                stockByAditionalImagesLog.StockId = stockByAditionalImages.StockId;
                                stockByAditionalImagesLog.ImageUrl = stockByAditionalImages.ImageUrl;
                                stockByAditionalImagesLog.NumImage = stockByAditionalImages.NumImage;

                                stockByAditionalImagesLog.TransactionDate = transactionDate;
                                stockByAditionalImagesLog.Tick = newTick;
                                stockByAditionalImagesLog.SyncTransaction = "D";
                                stockByAditionalImagesLog.TypeUserTransaction = typeUserTransaction;
                                stockByAditionalImagesLog.CompanyIdTransaction = stockEntity.CompanyId;
                                stockByAditionalImagesLog.UsernameTransaction = adminUsername;
                                stockByAditionalImagesLog.UuidTransaction = uuidTransaction;

                                GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesLogProvider.Insert(tm, stockByAditionalImagesLog);
                                GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesProvider.Delete(tm, stockByAditionalImages);
                                //stockFilesManagerServiceClient.DeleteStockItems(companyId, stockByAditionalImages.ImageUrl, null);
                            }
                            
                            stockLogEntity.CompanyId = stockEntity.CompanyId;
                            stockLogEntity.StockId = stockEntity.StockId;
                            stockLogEntity.StockCategoryId = stockEntity.StockCategoryId;

                            stockLogEntity.TransactionDate = transactionDate;
                            stockLogEntity.Tick = newTick;
                            stockLogEntity.SyncTransaction = "D";
                            stockLogEntity.UuidTransaction = uuidTransaction;

                            stockLogEntity.TypeUserTransaction = typeUserTransaction;
                            stockLogEntity.CompanyIdTransaction = stockEntity.CompanyId;
                            stockLogEntity.UsernameTransaction = adminUsername;

                            stockLogEntity.StockCode = stockEntity.StockCode;
                            stockLogEntity.StockBarCode = stockEntity.StockBarCode;
                            stockLogEntity.Name = stockEntity.Name;
                            stockLogEntity.Description = stockEntity.Description;
                            stockLogEntity.PromotionalNote = stockEntity.PromotionalNote;
                            stockLogEntity.Brand = stockEntity.Brand;
                            stockLogEntity.UnitStock = stockEntity.UnitStock;
                            stockLogEntity.UnitStockByBox = stockEntity.UnitStockByBox;
                            stockLogEntity.Quantity = stockEntity.Quantity;
                            stockLogEntity.MinQuantity = stockEntity.MinQuantity;
                            stockLogEntity.Price = stockEntity.Price;
                            stockLogEntity.ImageUrl = stockEntity.ImageUrl;
                            stockLogEntity.PdfDetailUrl = stockEntity.PdfDetailUrl;
                            stockLogEntity.ReservedQuantity = stockEntity.ReservedQuantity;

                            GPSTrackingDBV2.Data.DataRepository.StockLogProvider.Insert(tm, stockLogEntity);
                            GPSTrackingDBV2.Data.DataRepository.StockProvider.Delete(tm, stockEntity);

                            //stockFilesManagerServiceClient.DeleteStockItems(stockEntity.CompanyId, stockEntity.ImageUrl, stockEntity.PdfDetailUrl);
                            
                            tm.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        tm.Rollback();
                        stockEntityReturn.IsSync = false;
                        stockEntityReturn.Action = action;
                        stockEntityReturn.Message = ex.Message;
                    }
                    stockEntitiesReturn.Add(stockEntityReturn);
                    break;

                #endregion
            }

            return stockEntitiesReturn;

        }

        public List<Entities.StockByAditionalImages> SyncStockByAditionalImages(string action, int stockId, int companyId, int numImage, DateTime transactionDate, string tick, string uuidTransaction, int totalToGet)
        {
            Entities.StockByAditionalImages stockByAditionalImagesEntityReturn = new Entities.StockByAditionalImages();
            List<Entities.StockByAditionalImages> stockByAditionalImagesEntitiesReturn = new List<Entities.StockByAditionalImages>();

            GPSTrackingDBV2.Data.TransactionManager tm;

            GPSTrackingDBV2.Entities.StockByAditionalImagesLogByUuid stockByAditionalImagesLogByUuidEntity;

            switch (action)
            {
                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockByAditionalImagesLogByUuidProvider.GetToSync(uuidTransaction, companyId, totalToGet);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                stockByAditionalImagesEntityReturn = new Entities.StockByAditionalImages();

                                stockByAditionalImagesEntityReturn.Action = action;
                                stockByAditionalImagesEntityReturn.Total = total;

                                stockByAditionalImagesEntityReturn.StockId = int.Parse(row["StockID"].ToString());
                                stockByAditionalImagesEntityReturn.CompanyId = int.Parse(row["CompanyID"].ToString());
                                stockByAditionalImagesEntityReturn.NumImage = int.Parse(row["NumImage"].ToString());
                                stockByAditionalImagesEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                stockByAditionalImagesEntityReturn.Tick = row["Tick"].ToString();
                                stockByAditionalImagesEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                stockByAditionalImagesEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                stockByAditionalImagesEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                stockByAditionalImagesEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                stockByAditionalImagesEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();
                                stockByAditionalImagesEntityReturn.ImageUrl = row["ImageUrl"].ToString();

                                stockByAditionalImagesEntityReturn.IsSync = true;

                                stockByAditionalImagesEntitiesReturn.Add(stockByAditionalImagesEntityReturn);
                            }
                        }
                        else
                        {
                            stockByAditionalImagesEntityReturn.Action = action;
                            stockByAditionalImagesEntityReturn.Total = total;
                            stockByAditionalImagesEntityReturn.IsSync = true;
                            stockByAditionalImagesEntitiesReturn.Add(stockByAditionalImagesEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockByAditionalImagesEntitiesReturn.Clear();
                        stockByAditionalImagesEntityReturn.IsSync = false;
                        stockByAditionalImagesEntityReturn.Action = action;
                        stockByAditionalImagesEntityReturn.Message = ex.Message;
                        stockByAditionalImagesEntitiesReturn.Add(stockByAditionalImagesEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        stockByAditionalImagesEntityReturn.Total = GPSTrackingDBV2Custom.Data.DataRepository.StockByAditionalImagesLogByUuidProvider.GetTotalToSync(uuidTransaction, companyId);
                        stockByAditionalImagesEntityReturn.IsSync = true;
                        stockByAditionalImagesEntityReturn.Action = action;
                        stockByAditionalImagesEntitiesReturn.Add(stockByAditionalImagesEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        stockByAditionalImagesEntityReturn.IsSync = false;
                        stockByAditionalImagesEntityReturn.Action = action;
                        stockByAditionalImagesEntityReturn.Message = ex.Message;
                        stockByAditionalImagesEntitiesReturn.Add(stockByAditionalImagesEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        stockByAditionalImagesEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.StockByAditionalImagesLogByUuidProvider.UpdateSync(companyId, stockId, numImage, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            stockByAditionalImagesLogByUuidEntity = new StockByAditionalImagesLogByUuid();

                            stockByAditionalImagesLogByUuidEntity.StockId = stockId;
                            stockByAditionalImagesLogByUuidEntity.CompanyId = companyId;
                            stockByAditionalImagesLogByUuidEntity.NumImage = numImage;
                            stockByAditionalImagesLogByUuidEntity.TransactionDate = transactionDate;
                            stockByAditionalImagesLogByUuidEntity.Tick = Int64.Parse(tick);
                            stockByAditionalImagesLogByUuidEntity.Uuid = uuidTransaction;
                            stockByAditionalImagesLogByUuidEntity.IsSync = true;

                            stockByAditionalImagesEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesLogByUuidProvider.Insert(stockByAditionalImagesLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                stockByAditionalImagesEntityReturn.IsSync = false;
                                stockByAditionalImagesEntityReturn.Message = "No se actualizó el regisro de log de la imagen adicional." + ex.Message;
                            }
                        }
                        else
                        {
                            stockByAditionalImagesEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        stockByAditionalImagesEntityReturn.IsSync = false;
                        stockByAditionalImagesEntityReturn.Action = action;
                        stockByAditionalImagesEntityReturn.Message = ex.Message;
                    }
                    stockByAditionalImagesEntitiesReturn.Add(stockByAditionalImagesEntityReturn);

                    break;
                #endregion
            }

            return stockByAditionalImagesEntitiesReturn;

        }

        public List<Entities.StockCategories> SyncStockCategories(string action, int companyId, int stockCategoryId, string uuid, string tick, DateTime transactionDate)
        {
            Entities.StockCategories stockCategoriesEntityReturn = new Entities.StockCategories();
            GPSTrackingDBV2.Entities.StockCategoriesLogByUuid stockCategoriesLogByUuidEntity = new StockCategoriesLogByUuid();
            List<Entities.StockCategories> stockCategoriesEntitiesReturn = new List<Entities.StockCategories>();

            switch (action)
            {
                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesLogByUuidProvider.GetToSync(uuid, companyId);

                        int total = dt.Rows.Count;
                        

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                stockCategoriesEntityReturn = new Entities.StockCategories();
                                stockCategoriesEntityReturn.IsSync = true;
                                stockCategoriesEntityReturn.Action = action;
                                stockCategoriesEntityReturn.Total = total;

                                stockCategoriesEntityReturn.StockCategoryId = int.Parse(row["StockCategoryID"].ToString());
                                stockCategoriesEntityReturn.Name = row["Name"].ToString();
                                stockCategoriesEntityReturn.ImageUrl = row["ImageUrl"].ToString();
                                if (!String.IsNullOrEmpty(row["ParentStockCategoryID"].ToString()))
                                    stockCategoriesEntityReturn.ParentStockCategoryId = int.Parse(row["ParentStockCategoryID"].ToString());
                                stockCategoriesEntityReturn.Tick = row["Tick"].ToString();
                                stockCategoriesEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                stockCategoriesEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                stockCategoriesEntitiesReturn.Add(stockCategoriesEntityReturn);
                            }
                        }
                        else
                        {
                            stockCategoriesEntityReturn.IsSync = true;
                            stockCategoriesEntityReturn.Action = action;
                            stockCategoriesEntityReturn.Total = total;
                            stockCategoriesEntitiesReturn.Add(stockCategoriesEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockCategoriesEntityReturn.IsSync = false;
                        stockCategoriesEntityReturn.Action = action;
                        stockCategoriesEntityReturn.Message = ex.Message;
                        stockCategoriesEntitiesReturn.Add(stockCategoriesEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesLogByUuidProvider.GetToSync(uuid, companyId);

                        stockCategoriesEntityReturn.Total = dt.Rows.Count;
                        stockCategoriesEntityReturn.IsSync = true;
                        stockCategoriesEntityReturn.Action = action;
                        stockCategoriesEntitiesReturn.Add(stockCategoriesEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        stockCategoriesEntityReturn.IsSync = false;
                        stockCategoriesEntityReturn.Action = action;
                        stockCategoriesEntityReturn.Message = ex.Message;
                        stockCategoriesEntitiesReturn.Add(stockCategoriesEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        stockCategoriesEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesLogByUuidProvider.UpdateSync(stockCategoryId, uuid, Int64.Parse(tick), transactionDate))
                        {
                            stockCategoriesLogByUuidEntity = new StockCategoriesLogByUuid();

                            stockCategoriesLogByUuidEntity.StockCategoryId = stockCategoryId;
                            stockCategoriesLogByUuidEntity.TransactionDate = transactionDate;
                            stockCategoriesLogByUuidEntity.Tick = Int64.Parse(tick);
                            stockCategoriesLogByUuidEntity.Uuid = uuid;

                            stockCategoriesLogByUuidEntity.IsSync = true;
                            stockCategoriesEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.StockCategoriesLogByUuidProvider.Insert(stockCategoriesLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                stockCategoriesEntityReturn.IsSync = false;
                                stockCategoriesEntityReturn.Message = "No se actualizó el regisro de log de la categoría." + ex.Message;
                            }
                        }
                        else
                        {
                            stockCategoriesEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        stockCategoriesEntityReturn.IsSync = false;
                        stockCategoriesEntityReturn.Action = action;
                        stockCategoriesEntityReturn.Message = ex.Message;
                    }
                    stockCategoriesEntitiesReturn.Add(stockCategoriesEntityReturn);

                    break;
                #endregion
            }

            return stockCategoriesEntitiesReturn;

        }

        public void UnlinkApp(string uuid, int companyId, int applicationId)
        {
            try
            {
                GPSTrackingDBV2Custom.Data.DataRepository.ApplicationsProvider.UnlinkApp(uuid, companyId, applicationId);
            }
            catch (Exception ex){
                throw ex;
            }
           
        }

        public List<Entities.StockFilesTypeOfFile> SyncStockFilesTypeOfFile(string action, int stockFileTypeOfFileId, int companyId, DateTime transactionDate, string tick, string uuidTransaction)
        {
            Entities.StockFilesTypeOfFile stockFilesTypeOfFileEntityReturn = new Entities.StockFilesTypeOfFile();
            List<Entities.StockFilesTypeOfFile> stockFilesTypeOfFileEntitiesReturn = new List<Entities.StockFilesTypeOfFile>();

            GPSTrackingDBV2.Data.TransactionManager tm;

            GPSTrackingDBV2.Entities.StockFilesTypeOfFileLogByUuid stockFilesTypeOfFileLogByUuidEntity;

            switch (action)
            {
                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockFilesTypeOfFileLogByUuidProvider.GetToSync(uuidTransaction, companyId);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                stockFilesTypeOfFileEntityReturn = new Entities.StockFilesTypeOfFile();

                                stockFilesTypeOfFileEntityReturn.Action = action;
                                stockFilesTypeOfFileEntityReturn.Total = total;

                                stockFilesTypeOfFileEntityReturn.StockFileTypeOfFileId = int.Parse(row["StockFileTypeOfFileID"].ToString());
                                stockFilesTypeOfFileEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                stockFilesTypeOfFileEntityReturn.Tick = row["Tick"].ToString();
                                stockFilesTypeOfFileEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                stockFilesTypeOfFileEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                stockFilesTypeOfFileEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                stockFilesTypeOfFileEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                stockFilesTypeOfFileEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();
                                stockFilesTypeOfFileEntityReturn.Name = row["Name"].ToString();

                                stockFilesTypeOfFileEntityReturn.IsSync = true;

                                stockFilesTypeOfFileEntitiesReturn.Add(stockFilesTypeOfFileEntityReturn);
                            }
                        }
                        else
                        {
                            stockFilesTypeOfFileEntityReturn.Action = action;
                            stockFilesTypeOfFileEntityReturn.Total = total;
                            stockFilesTypeOfFileEntityReturn.IsSync = true;
                            stockFilesTypeOfFileEntitiesReturn.Add(stockFilesTypeOfFileEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockFilesTypeOfFileEntitiesReturn.Clear();
                        stockFilesTypeOfFileEntityReturn.IsSync = false;
                        stockFilesTypeOfFileEntityReturn.Action = action;
                        stockFilesTypeOfFileEntityReturn.Message = ex.Message;
                        stockFilesTypeOfFileEntitiesReturn.Add(stockFilesTypeOfFileEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockFilesTypeOfFileLogByUuidProvider.GetToSync(uuidTransaction, companyId);

                        stockFilesTypeOfFileEntityReturn.Total = dt.Rows.Count;
                        stockFilesTypeOfFileEntityReturn.IsSync = true;
                        stockFilesTypeOfFileEntityReturn.Action = action;
                        stockFilesTypeOfFileEntitiesReturn.Add(stockFilesTypeOfFileEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        stockFilesTypeOfFileEntityReturn.IsSync = false;
                        stockFilesTypeOfFileEntityReturn.Action = action;
                        stockFilesTypeOfFileEntityReturn.Message = ex.Message;
                        stockFilesTypeOfFileEntitiesReturn.Add(stockFilesTypeOfFileEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        stockFilesTypeOfFileEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.StockFilesTypeOfFileLogByUuidProvider.UpdateSync(stockFileTypeOfFileId, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            stockFilesTypeOfFileLogByUuidEntity = new StockFilesTypeOfFileLogByUuid();

                            stockFilesTypeOfFileLogByUuidEntity.StockFileTypeOfFileId = stockFileTypeOfFileId;
                            stockFilesTypeOfFileLogByUuidEntity.TransactionDate = transactionDate;
                            stockFilesTypeOfFileLogByUuidEntity.Tick = Int64.Parse(tick);
                            stockFilesTypeOfFileLogByUuidEntity.Uuid = uuidTransaction;
                            stockFilesTypeOfFileLogByUuidEntity.IsSync = true;

                            stockFilesTypeOfFileEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.StockFilesTypeOfFileLogByUuidProvider.Insert(stockFilesTypeOfFileLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                stockFilesTypeOfFileEntityReturn.IsSync = false;
                                stockFilesTypeOfFileEntityReturn.Message = "No se actualizó el regisro de log del tipo de producto." + ex.Message;
                            }
                        }
                        else
                        {
                            stockFilesTypeOfFileEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        stockFilesTypeOfFileEntityReturn.IsSync = false;
                        stockFilesTypeOfFileEntityReturn.Action = action;
                        stockFilesTypeOfFileEntityReturn.Message = ex.Message;
                    }
                    stockFilesTypeOfFileEntitiesReturn.Add(stockFilesTypeOfFileEntityReturn);

                    break;
                #endregion
            }

            return stockFilesTypeOfFileEntitiesReturn;

        }

        public List<Entities.StockFilesByUsername> SyncStockFilesByUsername(string action, int stockFileId, string username, int companyId, DateTime transactionDate, string tick, string uuidTransaction)
        {
            Entities.StockFilesByUsername stockFilesByUsernameEntityReturn = new Entities.StockFilesByUsername();
            List<Entities.StockFilesByUsername> stockFilesByUsernameEntitiesReturn = new List<Entities.StockFilesByUsername>();

            GPSTrackingDBV2.Data.TransactionManager tm;

            GPSTrackingDBV2.Entities.StockFilesByUsernameLogByUuid stockFilesByUsernameLogByUuidEntity;

            switch (action)
            {
                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockFilesByUsernameLogByUuidProvider.GetToSync(uuidTransaction, companyId);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                stockFilesByUsernameEntityReturn = new Entities.StockFilesByUsername();

                                stockFilesByUsernameEntityReturn.Action = action;
                                stockFilesByUsernameEntityReturn.Total = total;

                                stockFilesByUsernameEntityReturn.StockFileId = int.Parse(row["StockFileID"].ToString());
                                stockFilesByUsernameEntityReturn.CompanyId = int.Parse(row["CompanyID"].ToString());
                                stockFilesByUsernameEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                stockFilesByUsernameEntityReturn.Tick = row["Tick"].ToString();
                                stockFilesByUsernameEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                stockFilesByUsernameEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                stockFilesByUsernameEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                stockFilesByUsernameEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                stockFilesByUsernameEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();
                                stockFilesByUsernameEntityReturn.Username = row["Username"].ToString();
                                
                                stockFilesByUsernameEntityReturn.IsSync = true;

                                stockFilesByUsernameEntitiesReturn.Add(stockFilesByUsernameEntityReturn);
                            }
                        }
                        else
                        {
                            stockFilesByUsernameEntityReturn.Action = action;
                            stockFilesByUsernameEntityReturn.Total = total;
                            stockFilesByUsernameEntityReturn.IsSync = true;
                            stockFilesByUsernameEntitiesReturn.Add(stockFilesByUsernameEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockFilesByUsernameEntitiesReturn.Clear();
                        stockFilesByUsernameEntityReturn.IsSync = false;
                        stockFilesByUsernameEntityReturn.Action = action;
                        stockFilesByUsernameEntityReturn.Message = ex.Message;
                        stockFilesByUsernameEntitiesReturn.Add(stockFilesByUsernameEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockFilesByUsernameLogByUuidProvider.GetToSync(uuidTransaction, companyId);

                        stockFilesByUsernameEntityReturn.Total = dt.Rows.Count;
                        stockFilesByUsernameEntityReturn.IsSync = true;
                        stockFilesByUsernameEntityReturn.Action = action;
                        stockFilesByUsernameEntitiesReturn.Add(stockFilesByUsernameEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        stockFilesByUsernameEntityReturn.IsSync = false;
                        stockFilesByUsernameEntityReturn.Action = action;
                        stockFilesByUsernameEntityReturn.Message = ex.Message;
                        stockFilesByUsernameEntitiesReturn.Add(stockFilesByUsernameEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        stockFilesByUsernameEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.StockFilesByUsernameLogByUuidProvider.UpdateSync(companyId, stockFileId, username, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            stockFilesByUsernameLogByUuidEntity = new StockFilesByUsernameLogByUuid();

                            stockFilesByUsernameLogByUuidEntity.StockFileId = stockFileId;
                            stockFilesByUsernameLogByUuidEntity.CompanyId = companyId;
                            stockFilesByUsernameLogByUuidEntity.Username = username;
                            stockFilesByUsernameLogByUuidEntity.TransactionDate = transactionDate;
                            stockFilesByUsernameLogByUuidEntity.Tick = Int64.Parse(tick);
                            stockFilesByUsernameLogByUuidEntity.Uuid = uuidTransaction;
                            stockFilesByUsernameLogByUuidEntity.IsSync = true;

                            stockFilesByUsernameEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.StockFilesByUsernameLogByUuidProvider.Insert(stockFilesByUsernameLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                stockFilesByUsernameEntityReturn.IsSync = false;
                                stockFilesByUsernameEntityReturn.Message = "No se actualizó el regisro de log del tipo de producto por usuario." + ex.Message;
                            }
                        }
                        else
                        {
                            stockFilesByUsernameEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        stockFilesByUsernameEntityReturn.IsSync = false;
                        stockFilesByUsernameEntityReturn.Action = action;
                        stockFilesByUsernameEntityReturn.Message = ex.Message;
                    }
                    stockFilesByUsernameEntitiesReturn.Add(stockFilesByUsernameEntityReturn);

                    break;
                #endregion
            }

            return stockFilesByUsernameEntitiesReturn;

        }

        public List<Entities.StockFiles> SyncStockFiles(string action, int stockFileId, int companyId, DateTime transactionDate, string tick, string uuidTransaction)
        {
            Entities.StockFiles stockFilesEntityReturn = new Entities.StockFiles();
            List<Entities.StockFiles> stockFilesEntitiesReturn = new List<Entities.StockFiles>();

            GPSTrackingDBV2.Data.TransactionManager tm;

            GPSTrackingDBV2.Entities.StockFilesLogByUuid stockFilesLogByUuidEntity;

            switch (action)
            {
                #region GetToSync

                case "GetToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockFilesLogByUuidProvider.GetToSync(uuidTransaction, companyId);

                        int total = dt.Rows.Count;

                        if (total > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                stockFilesEntityReturn = new Entities.StockFiles();

                                stockFilesEntityReturn.Action = action;
                                stockFilesEntityReturn.Total = total;

                                stockFilesEntityReturn.StockFileId = int.Parse(row["StockFileID"].ToString());
                                stockFilesEntityReturn.CompanyId = int.Parse(row["CompanyID"].ToString());
                                stockFilesEntityReturn.Name = row["Name"].ToString();
                                stockFilesEntityReturn.FileName = row["FileName"].ToString();
                                stockFilesEntityReturn.StockFileTypeOfFileId = int.Parse(row["StockFileTypeOfFileID"].ToString());
                                stockFilesEntityReturn.TransactionDate = row["TransactionDateString"].ToString();
                                stockFilesEntityReturn.Tick = row["Tick"].ToString();
                                stockFilesEntityReturn.SyncTransaction = row["SyncTransaction"].ToString();
                                stockFilesEntityReturn.TypeUserTransaction = row["TypeUserTransaction"].ToString();
                                stockFilesEntityReturn.CompanyIdTransaction = int.Parse(row["CompanyIdTransaction"].ToString());
                                stockFilesEntityReturn.UsernameTransaction = row["UsernameTransaction"].ToString();
                                stockFilesEntityReturn.UuidTransaction = row["UuidTransaction"].ToString();

                                stockFilesEntityReturn.IsSync = true;

                                stockFilesEntitiesReturn.Add(stockFilesEntityReturn);
                            }
                        }
                        else
                        {
                            stockFilesEntityReturn.Action = action;
                            stockFilesEntityReturn.Total = total;
                            stockFilesEntityReturn.IsSync = true;
                            stockFilesEntitiesReturn.Add(stockFilesEntityReturn);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockFilesEntitiesReturn.Clear();
                        stockFilesEntityReturn.IsSync = false;
                        stockFilesEntityReturn.Action = action;
                        stockFilesEntityReturn.Message = ex.Message;
                        stockFilesEntitiesReturn.Add(stockFilesEntityReturn);
                    }

                    break;
                #endregion

                #region GetTotalToSync

                case "GetTotalToSync":

                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockFilesLogByUuidProvider.GetToSync(uuidTransaction, companyId);

                        stockFilesEntityReturn.Total = dt.Rows.Count;
                        stockFilesEntityReturn.IsSync = true;
                        stockFilesEntityReturn.Action = action;
                        stockFilesEntitiesReturn.Add(stockFilesEntityReturn);

                    }
                    catch (Exception ex)
                    {
                        stockFilesEntityReturn.IsSync = false;
                        stockFilesEntityReturn.Action = action;
                        stockFilesEntityReturn.Message = ex.Message;
                        stockFilesEntitiesReturn.Add(stockFilesEntityReturn);
                    }

                    break;
                #endregion

                #region SetSyncTrue

                case "SetSyncTrue":

                    try
                    {
                        stockFilesEntityReturn.Action = action;

                        if (!GPSTrackingDBV2Custom.Data.DataRepository.StockFilesLogByUuidProvider.UpdateSync(companyId, stockFileId, uuidTransaction, Int64.Parse(tick), transactionDate))
                        {
                            stockFilesLogByUuidEntity = new StockFilesLogByUuid();

                            stockFilesLogByUuidEntity.StockFileId = stockFileId;
                            stockFilesLogByUuidEntity.CompanyId = companyId;
                            stockFilesLogByUuidEntity.TransactionDate = transactionDate;
                            stockFilesLogByUuidEntity.Tick = Int64.Parse(tick);
                            stockFilesLogByUuidEntity.Uuid = uuidTransaction;
                            stockFilesLogByUuidEntity.IsSync = true;

                            stockFilesEntityReturn.IsSync = true;

                            try
                            {
                                GPSTrackingDBV2.Data.DataRepository.StockFilesLogByUuidProvider.Insert(stockFilesLogByUuidEntity);
                            }
                            catch (Exception ex)
                            {
                                stockFilesEntityReturn.IsSync = false;
                                stockFilesEntityReturn.Message = "No se actualizó el regisro de log del archivo de producto." + ex.Message;
                            }
                        }
                        else
                        {
                            stockFilesEntityReturn.IsSync = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        stockFilesEntityReturn.IsSync = false;
                        stockFilesEntityReturn.Action = action;
                        stockFilesEntityReturn.Message = ex.Message;
                    }
                    stockFilesEntitiesReturn.Add(stockFilesEntityReturn);

                    break;
                #endregion
            }

            return stockFilesEntitiesReturn;

        }
        
        public string ConvertDateFormatToISOString(DateTime date)
        {

            string strYear = date.Year.ToString().PadLeft(4, '0');
            string strMonth = date.Month.ToString().PadLeft(2, '0');
            string strDay = date.Day.ToString().PadLeft(2, '0');
            string strHours = date.Hour.ToString().PadLeft(2, '0');
            string strMinutes = date.Minute.ToString().PadLeft(2, '0');
            string strSeconds = date.Second.ToString().PadLeft(2, '0');
            string strMilliseconds = date.Millisecond.ToString().PadLeft(3, '0');

            return strYear + "-" + strMonth + "-" + strDay + " " + strHours + ":" + strMinutes + ":" + strSeconds + "." + strMilliseconds;
        }

        public string DecodingUrlValue(string value)
        {

            value = value.Replace("%20", " ");
            value = value.Replace("%21", "!");
            value = value.Replace("%23", "#");
            value = value.Replace("%24", "$");
            value = value.Replace("%25", "%");
            value = value.Replace("%26", "&");
            value = value.Replace("%27", "'");
            value = value.Replace("%28", "(");
            value = value.Replace("%29", ")");
            value = value.Replace("%2A", "*");
            value = value.Replace("%2B", "+");
            value = value.Replace("%2C", ",");
            value = value.Replace("%2D", "-");
            value = value.Replace("%2F", "/");
            value = value.Replace("%3A", ":");
            value = value.Replace("%3B", ";");
            value = value.Replace("%3C", "<");
            value = value.Replace("%3D", "=");
            value = value.Replace("%3E", ">");
            value = value.Replace("%3F", "?");
            value = value.Replace("%40", "@");
            value = value.Replace("%5B", "[");
            value = value.Replace("%5C", "\\");
            value = value.Replace("%5D", "]");
            value = value.Replace("%5E", "^");
            value = value.Replace("%5F", "_");
            value = value.Replace("%60", "`");
            value = value.Replace("%7B", "{");
            value = value.Replace("%7C", "|");
            value = value.Replace("%7D", "}");
            value = value.Replace("%7E", "~");
            value = value.Replace("%80", "`");
            value = value.Replace("%82", "‚");
            value = value.Replace("%91", "‘");
            value = value.Replace("%92", "’");
            value = value.Replace("%A1", "¡");
            value = value.Replace("%A2", "¢");
            value = value.Replace("%BF", "¿");
            value = value.Replace("%C1", "Á");
            value = value.Replace("%C9", "É");
            value = value.Replace("%CD", "Í");
            value = value.Replace("%D3", "Ó");
            value = value.Replace("%DA", "Ú");
            value = value.Replace("%E1", "á");
            value = value.Replace("%E9", "é");
            value = value.Replace("%ED", "í");
            value = value.Replace("%F3", "ó");
            value = value.Replace("%FA","ú");
            value = value.Replace("%22", "\"");

            return value;
        }

        public Entities.ObjectResult<object> StartEmailSendingProcess(int companyId, string username)
        {
            Entities.ObjectResult<object> result = new Entities.ObjectResult<object>();

            try{             
               

                System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Start Email Sending Process");

                DataSet dtEmailPending = GPSTrackingDBV2Custom.Data.DataRepository.EmailToSendStocksProvider.GetEmailPending(companyId, username);

                List<Entities.EmailToSendStocksPendings> emailToSendStocksPendingsEntities = Entities.EmailToSendStocksPendings.ConvertToEmailToSendStocksPendingsEntities(dtEmailPending.Tables[0]);

                System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Email To Send Stocks Pendings Entities");


                var distintClients = Entities.EmailToSendStocksPendings.ConvertToDistincEmailToSendStocksPendingsEntities(dtEmailPending.Tables[1]);              

                foreach (var clientEntity in distintClients)
                {
                    System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Send Loop for Clients");                    
                    
                    var stockToSend = emailToSendStocksPendingsEntities.Where(w => w.ClientID == clientEntity.ClientID && w.EmailToSendStockID == clientEntity.EmailToSendStockID);

                    //Find client
                    GPSTrackingDBV2.Entities.Clients clientInfoEntity = GPSTrackingDBV2.Data.DataRepository.ClientsProvider.GetByClientId(clientEntity.ClientID);

                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(System.Configuration.ConfigurationManager.AppSettings["BodyHeaderText"].Replace("{Name}", clientInfoEntity.Name));
                    sb.AppendLine("");                
                    
                    DataTable dtInvoice = new DataTable();
                    dtInvoice.Columns.Add("Code");
                    dtInvoice.Columns.Add("Product");
                    dtInvoice.Columns.Add("Quantity");
                                        
                    List<EmailManager.EmailManager.CustomAttachments> listAttachment = new List<EmailManager.EmailManager.CustomAttachments>();


                    StringBuilder sbRows = new StringBuilder();
                    System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Generate list of stock to send");
                    foreach (var stockEntity in stockToSend)
                    {                    
                        GPSTrackingDBV2.Entities.Stock stockInfoEntity = GPSTrackingDBV2.Data.DataRepository.StockProvider.GetByCompanyIdStockId(stockEntity.CompanyID, stockEntity.StockID);

                        if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["SendStockListText"]))
                        {
                            sbRows.AppendLine("<tr>");
                            sbRows.AppendLine("<td class='service'>" + stockInfoEntity.StockCode+ "</td>");
                            sbRows.AppendLine("<td class='desc'>" + stockInfoEntity.Name+ "</td>");
                            sbRows.AppendLine("<td class='unit'>"+stockEntity.ReservedQuantity.ToString()+"</td>");
                            sbRows.AppendLine("</tr>");
                        }

                        if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["SendInvoicePDF"]))
                        {
                            DataRow row = dtInvoice.NewRow();
                            row["Code"] = stockInfoEntity.StockCode;
                            row["Product"] = stockInfoEntity.Name;
                            row["Quantity"] = stockEntity.ReservedQuantity;

                            dtInvoice.Rows.Add(row);
                        }


                        if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["SendStockPDFFile"]))
                        {
                            if (!String.IsNullOrEmpty(stockInfoEntity.PdfDetailUrl))
                            {
                                //Get PDf
                                StockFilesManagerService.StockFilesManagerServiceClient stockFilesManagerServiceClient = new StockFilesManagerService.StockFilesManagerServiceClient();
                                byte[] fileBytes = stockFilesManagerServiceClient.GetStockFile(stockEntity.CompanyID, stockEntity.StockID);

                                System.IO.Stream stream = new System.IO.MemoryStream(fileBytes);

                                EmailManager.EmailManager.CustomAttachments customAttachments = new EmailManager.EmailManager.CustomAttachments();
                                customAttachments.Filename = stockInfoEntity.PdfDetailUrl;
                                customAttachments.FileStream = stream;

                                listAttachment.Add(customAttachments);
                            }
                        }
                    }
                    //Build Invoice Html
                    sb.AppendLine(GetTemporalInvoice(clientEntity.EmailToSendStockID.ToString(), sbRows.ToString()));


                    //Invoice PDF
                    if(clientEntity.IsSendInvoice)
                    //if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["SendInvoicePDF"]))
                    {
                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Generate Invoice PDF");

                        Invoice.Invoice rpt = new Invoice.Invoice();
                        StockFilesManagerService.StockFilesManagerServiceClient stockFilesManagerServiceClient = new StockFilesManagerService.StockFilesManagerServiceClient();
                        byte[] companyLogoBytes = stockFilesManagerServiceClient.GetCompanyLogo(companyId);

                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Get logo from StockFilesManagerServiceClient");
                        System.Drawing.Image companyLogo = byteArrayToImage(companyLogoBytes);
                        rpt.SetParameters(companyId, companyLogo, dtInvoice, System.Configuration.ConfigurationManager.AppSettings["BodyHeaderPDF"].Replace("{Name}", clientInfoEntity.Name), "Proforma Nº: " + clientEntity.EmailToSendStockID);

                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Export report to PDF");
                        MemoryStream memoryStream = ExportToPDF(rpt);

                        byte[] rptBytes = memoryStream.GetBuffer();
                        System.IO.Stream streamRpt = new System.IO.MemoryStream(rptBytes);

                        EmailManager.EmailManager.CustomAttachments customInvoiceAttachments = new EmailManager.EmailManager.CustomAttachments();
                        customInvoiceAttachments.Filename = System.Configuration.ConfigurationManager.AppSettings["InvoicePDFName"].Replace("{Num}", clientEntity.EmailToSendStockID.ToString()).Replace("{Name}",clientInfoEntity.Name);
                        customInvoiceAttachments.FileStream = streamRpt;

                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Attachment PDF");

                        listAttachment.Add(customInvoiceAttachments);
                    }

                    //Find all email by clients
                    System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Find all email from clients");
                    List<string> listAddress = new List<string>();
                    GPSTrackingDBV2.Entities.TList<ClientsByEmail> ClientsByEmailEntities = GPSTrackingDBV2.Data.DataRepository.ClientsByEmailProvider.GetByClientId(clientEntity.ClientID);
                    foreach(ClientsByEmail clientsByEmailEntity in ClientsByEmailEntities)
                    {
                        listAddress.Add(clientsByEmailEntity.Email);
                    }

                    System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Send email to agent");
                    //Copy to Agent
                    List<string> listCC = new List<string>();
                    GPSTrackingDBV2.Entities.Users userEntity = GPSTrackingDBV2.Data.DataRepository.UsersProvider.GetByUsernameCompanyId(username, companyId);
                    listCC.Add(userEntity.Email);

                    try
                    {
                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Sending email");
                        bool isHtmlBody = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsHtmlBody"]);
                        EmailManager.EmailManager.Send(listAddress, listCC, clientEntity.CompanyName + "-" + System.Configuration.ConfigurationManager.AppSettings["SubjectText"].Replace("{Num}",clientEntity.EmailToSendStockID.ToString()), sb.ToString(), isHtmlBody, listAttachment);

                        //Update record PEE to ENF
                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Update record PEE to ENF");
                        GPSTrackingDBV2.Entities.EmailToSendStocks emailToSendStocksEntity = GPSTrackingDBV2.Data.DataRepository.EmailToSendStocksProvider.GetByCompanyIdEmailToSendStockId(clientEntity.CompanyID, clientEntity.EmailToSendStockID);
                        emailToSendStocksEntity.StatusId = "ENF";
                        emailToSendStocksEntity.OriginalCompanyId = emailToSendStocksEntity.CompanyId;
                        emailToSendStocksEntity.OriginalEmailToSendStockId = emailToSendStocksEntity.EmailToSendStockId;

                        GPSTrackingDBV2.Data.DataRepository.EmailToSendStocksProvider.Update(emailToSendStocksEntity);
                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess> Finish sending email");                        
                    
                    }
                    catch (System.Net.Mail.SmtpException ex)
                    {

                        System.Diagnostics.Trace.WriteLine("StartEmailSendingProcess>SmtpException> Error - " + GetMessageException(ex));                        

                        GPSTrackingDBCustom.Log.WindowsServiceLog.Error(ex.Message, "EmailManager");
                    }

                }                
            }
            catch(Exception ex){

                //throw new Exception("No se envío los correos: Error: " + ex.Message.ToString());
                result.code = "99";
                result.isSuccessfull = false;
                result.isSuccessful = false;
                result.description = "No se envío los correos";
                result.descriptionDetail = "Error Message: " + ex.Message != null ? ex.Message : string.Empty + " Error Exception: " + ex.InnerException != null ? ex.InnerException.ToString() : string.Empty;

                System.Diagnostics.Trace.WriteLine(result.descriptionDetail);  
            }

            return result;
        }

        private MemoryStream ExportToPDF(Telerik.Reporting.Report reportToExport)
        {
            ReportProcessor reportProcessor = new ReportProcessor();
            Telerik.Reporting.InstanceReportSource instanceReportSource = new Telerik.Reporting.InstanceReportSource();
            instanceReportSource.ReportDocument = reportToExport;
            RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, null);

            MemoryStream ms = new MemoryStream();
            ms.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);

            return ms;
            
        }

        public List<Entities.StockSettingValues> StockSettingManager(string action, int companyId, int stockSettingId, string adminUsername, string name, string values) {

            List<Entities.StockSettingValues> stockSettingEntitiesReturn = new List<Entities.StockSettingValues>();
            
            Entities.StockSettingValues stockSetting = new Entities.StockSettingValues();

            GPSTrackingDBV2.Entities.StockSetting stockSettingEntity = new GPSTrackingDBV2.Entities.StockSetting();
            GPSTrackingDBV2.Entities.StockSettingValues stockSettingValuesEntity = new GPSTrackingDBV2.Entities.StockSettingValues();
            TList<GPSTrackingDBV2.Entities.StockSettingValues> stockSettingValuesEntities = new TList<StockSettingValues>();

            DataContractJsonSerializer ser = null;
            MemoryStream stream = null;

            GPSTrackingDBV2.Data.TransactionManager tm;
            
            switch (action)
            {

                case "GetStockSetting":
                    try
                    {
                        DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockSettingProvider.GetByCompanyId(companyId);

                        foreach (DataRow row in dt.Rows)
                        {

                            stockSetting = new Entities.StockSettingValues();

                            stockSetting.CompanyId = int.Parse(row["CompanyID"].ToString());
                            stockSetting.StockSettingId = int.Parse(row["StockSettingID"].ToString());
                            stockSetting.Name = row["Name"].ToString();

                            stockSettingEntitiesReturn.Add(stockSetting);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockSetting.Message = ex.Message;
                        stockSettingEntitiesReturn.Clear();
                        stockSettingEntitiesReturn.Add(stockSetting);
                    }
                    break;

                case "GetStockSettingValues":
                    try
                    {
                        stockSettingValuesEntities = GPSTrackingDBV2.Data.DataRepository.StockSettingValuesProvider.GetByCompanyIdStockSettingId(companyId, stockSettingId);

                        foreach (GPSTrackingDBV2.Entities.StockSettingValues entity in stockSettingValuesEntities)
                        {

                            stockSetting = new Entities.StockSettingValues();

                            stockSetting.CompanyId = entity.CompanyId;
                            stockSetting.StockSettingId = entity.StockSettingId;
                            stockSetting.KeyValue = entity.KeyValue;
                            stockSetting.Value = entity.Value;
                            stockSetting.Type = entity.Type;

                            stockSettingEntitiesReturn.Add(stockSetting);
                        }
                    }
                    catch (Exception ex)
                    {
                        stockSetting.Message = ex.Message;
                        stockSettingEntitiesReturn.Clear();
                        stockSettingEntitiesReturn.Add(stockSetting);
                    }

                    break;
                case "InsertStockSettingValues":

                    if(!String.IsNullOrEmpty(values)){
                        values = DecodingUrlValue(values);
                        name = DecodingUrlValue(name);
                        ser = new DataContractJsonSerializer(typeof(List<Entities.StockSettingValues>)); 
                        stream = new MemoryStream(Encoding.UTF8.GetBytes(values));
                        var objInsertStockSettingValues = (List<Entities.StockSettingValues>)ser.ReadObject(stream);

                        tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                        try
                        {
                            tm.BeginTransaction();
                            
                            stockSettingId = GPSTrackingDBV2Custom.Data.DataRepository.StockSettingProvider.GetNextID(companyId);

                            stockSettingEntity.CompanyId = companyId;
                            stockSettingEntity.StockSettingId = stockSettingId;
                            stockSettingEntity.Name = name;
                            stockSettingEntity.AdminUsername = adminUsername;
                            stockSettingEntity.TransactionDate = DateTime.Now;
                            stockSettingEntity.IsActive = true;

                            foreach (Entities.StockSettingValues entity in objInsertStockSettingValues)
                            {
                                stockSettingValuesEntity = new StockSettingValues();

                                stockSettingValuesEntity.CompanyId = companyId;
                                stockSettingValuesEntity.StockSettingId = stockSettingId;
                                stockSettingValuesEntity.KeyValue = entity.KeyValue;
                                stockSettingValuesEntity.Value = entity.Value;
                                stockSettingValuesEntity.Type = entity.Type;

                                stockSettingValuesEntities.Add(stockSettingValuesEntity);
                            }

                            
                            GPSTrackingDBV2.Data.DataRepository.StockSettingProvider.Insert(tm, stockSettingEntity);
                            GPSTrackingDBV2.Data.DataRepository.StockSettingValuesProvider.Insert(tm, stockSettingValuesEntities);
                            tm.Commit();
                        }
                        catch (Exception ex) {
                            tm.Rollback();
                            stockSetting.Message = ex.Message;
                            stockSettingEntitiesReturn.Clear();
                            stockSettingEntitiesReturn.Add(stockSetting);
                        }

                    }

                    break;
                case "UpdateStockSetting":

                    name = DecodingUrlValue(name);

                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                    try
                    {
                        tm.BeginTransaction();
                            
                        stockSettingEntity = new GPSTrackingDBV2.Entities.StockSetting();

                        stockSettingEntity.CompanyId = companyId;
                        stockSettingEntity.OriginalCompanyId = companyId;
                        stockSettingEntity.StockSettingId = stockSettingId;
                        stockSettingEntity.OriginalStockSettingId = stockSettingId;
                        stockSettingEntity.TransactionDate = DateTime.Now;
                        stockSettingEntity.AdminUsername = adminUsername;
                        stockSettingEntity.Name = name;
                        stockSettingEntity.IsActive = true;
                                                        
                        GPSTrackingDBV2.Data.DataRepository.StockSettingProvider.Update(tm, stockSettingEntity);
                        tm.Commit();
                    }
                    catch (Exception ex)
                    {
                        tm.Rollback();
                        stockSetting.Message = ex.Message;
                        stockSettingEntitiesReturn.Clear();
                        stockSettingEntitiesReturn.Add(stockSetting);
                    }

                    

                    break;
                case "UpdateStockSettingValues":

                    if (!String.IsNullOrEmpty(values))
                    {
                        values = DecodingUrlValue(values);

                        ser = new DataContractJsonSerializer(typeof(List<Entities.StockSettingValues>));
                        stream = new MemoryStream(Encoding.UTF8.GetBytes(values));
                        var objUpdateStockSettingValues = (List<Entities.StockSettingValues>)ser.ReadObject(stream);

                        tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                        try
                        { 
                            tm.BeginTransaction();

                            foreach (Entities.StockSettingValues entity in objUpdateStockSettingValues)
                            {
                                stockSettingValuesEntity = new StockSettingValues();

                                stockSettingValuesEntity.CompanyId = companyId;
                                stockSettingValuesEntity.StockSettingId = stockSettingId;
                                stockSettingValuesEntity.KeyValue = entity.KeyValue;
                                stockSettingValuesEntity.Value = entity.Value;
                                stockSettingValuesEntity.Type = entity.Type;

                                stockSettingValuesEntities.Add(stockSettingValuesEntity);
                            }

                            GPSTrackingDBV2.Data.DataRepository.StockSettingValuesProvider.Delete(tm, stockSettingValuesEntities);
                            GPSTrackingDBV2.Data.DataRepository.StockSettingValuesProvider.Insert(tm, stockSettingValuesEntities);
                            tm.Commit();
                        }
                        catch (Exception ex)
                        {
                            tm.Rollback();
                            stockSetting.Message = ex.Message;
                            stockSettingEntitiesReturn.Clear();
                            stockSettingEntitiesReturn.Add(stockSetting);
                        }

                    }

                    break;
                case "DeleteStockSetting":

                    name = DecodingUrlValue(name);

                    tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

                    try
                    {
                        tm.BeginTransaction();
                            
                        stockSettingEntity = new GPSTrackingDBV2.Entities.StockSetting();

                        stockSettingEntity.CompanyId = companyId;
                        stockSettingEntity.OriginalCompanyId = companyId;
                        stockSettingEntity.StockSettingId = stockSettingId;
                        stockSettingEntity.OriginalStockSettingId = stockSettingId;
                        stockSettingEntity.TransactionDate = DateTime.Now;
                        stockSettingEntity.AdminUsername = adminUsername;
                        stockSettingEntity.IsActive = false;
                                                        
                        GPSTrackingDBV2.Data.DataRepository.StockSettingProvider.Update(tm, stockSettingEntity);
                        tm.Commit();
                    }
                    catch (Exception ex)
                    {
                        tm.Rollback();
                        stockSetting.Message = ex.Message;
                        stockSettingEntitiesReturn.Clear();
                        stockSettingEntitiesReturn.Add(stockSetting);
                    }

                    break;
            }

            return stockSettingEntitiesReturn;
        }

        public void SyncCatalogStatistics(string action, int companyId, string uuidTransaction, string visorValue, DateTime beginDatetime, DateTime endDatetime, string typeUser, string username)
        {
            switch(action){
                case "InsertCatalogStatistics":
                    
                    using (EntityFrameworkManager.FalconSystemDBEntities FalconSystemDBProvider = new EntityFrameworkManager.FalconSystemDBEntities())
                    {
                        EntityFrameworkManager.CatalogStatistics catalogStatisticsEntity = new EntityFrameworkManager.CatalogStatistics();
                        catalogStatisticsEntity.CompanyID = companyId;
                        catalogStatisticsEntity.Uuid = uuidTransaction;
                        catalogStatisticsEntity.VisorValue = DecodingUrlValue(visorValue);
                        catalogStatisticsEntity.BeginDatetime = beginDatetime;
                        catalogStatisticsEntity.EndDatetime = endDatetime;
                        catalogStatisticsEntity.TypeUser = typeUser;
                        catalogStatisticsEntity.Username = username;
                        FalconSystemDBProvider.CatalogStatistics.Add(catalogStatisticsEntity);
                        FalconSystemDBProvider.SaveChanges();
                    }

                    break;
            }
        }

        private Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private string GetMessageException(Exception ex)
        {
            string message = "Message: " + ex.Message;
            if (ex.InnerException != null)
            {
                message += " InnerException: " + ex.InnerException.ToString();
            }

            return message;
        }

        private string GetTemporalInvoice(string invoiceNumber, string rows)
        {
            string html = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "/Invoice/Invoice.html");
            html = html.Replace("[INVOICENUMBER]", "Proforma Nº: " + invoiceNumber);
            html = html.Replace("[TR_ROWS]", rows);

            return html;               
        }

    }
}
